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 [`ScoreLookUp`] implementation is not needed.
17 //! # extern crate bitcoin;
19 //! # use lightning::routing::gossip::NetworkGraph;
20 //! # use lightning::routing::router::{RouteParameters, find_route};
21 //! # use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
22 //! # use lightning::sign::KeysManager;
23 //! # use lightning::util::logger::{Logger, Record};
24 //! # use bitcoin::secp256k1::PublicKey;
26 //! # struct FakeLogger {};
27 //! # impl Logger for FakeLogger {
28 //! # fn log(&self, record: &Record) { unimplemented!() }
30 //! # fn find_scored_route(payer: PublicKey, route_params: RouteParameters, network_graph: NetworkGraph<&FakeLogger>) {
31 //! # let logger = FakeLogger {};
33 //! // Use the default channel penalties.
34 //! let params = ProbabilisticScoringFeeParameters::default();
35 //! let decay_params = ProbabilisticScoringDecayParameters::default();
36 //! let scorer = ProbabilisticScorer::new(decay_params, &network_graph, &logger);
38 //! // Or use custom channel penalties.
39 //! let params = ProbabilisticScoringFeeParameters {
40 //! \tliquidity_penalty_multiplier_msat: 2 * 1000,
41 //! \t..ProbabilisticScoringFeeParameters::default()
43 //! let decay_params = ProbabilisticScoringDecayParameters::default();
44 //! let scorer = ProbabilisticScorer::new(decay_params, &network_graph, &logger);
45 //! # let random_seed_bytes = [42u8; 32];
47 //! let route = find_route(&payer, &route_params, &network_graph, None, &logger, &scorer, ¶ms, &random_seed_bytes);
53 //! Persisting when built with feature `no-std` and restoring without it, or vice versa, uses
54 //! different types and thus is undefined.
56 //! [`find_route`]: crate::routing::router::find_route
58 use alloc::str::FromStr;
59 use alloc::string::String;
60 use core::ffi::c_void;
61 use core::convert::Infallible;
62 use bitcoin::hashes::Hash;
63 use crate::c_types::*;
64 #[cfg(feature="no-std")]
65 use alloc::{vec::Vec, boxed::Box};
67 /// An interface used to score payment channels for path finding.
69 /// `ScoreLookUp` is used to determine the penalty for a given channel.
71 /// Scoring is in terms of fees willing to be paid in order to avoid routing through a channel.
73 pub struct ScoreLookUp {
74 /// An opaque pointer which is passed to your function implementations as an argument.
75 /// This has no meaning in the LDK, and can be NULL or any other value.
76 pub this_arg: *mut c_void,
77 /// Returns the fee in msats willing to be paid to avoid routing `send_amt_msat` through the
78 /// given channel in the direction from `source` to `target`.
80 /// The channel's capacity (less any other MPP parts that are also being considered for use in
81 /// the same payment) is given by `capacity_msat`. It may be determined from various sources
82 /// such as a chain data, network gossip, or invoice hints. For invoice hints, a capacity near
83 /// [`u64::max_value`] is given to indicate sufficient capacity for the invoice's full amount.
84 /// Thus, implementations should be overflow-safe.
85 pub channel_penalty_msat: extern "C" fn (this_arg: *const c_void, short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, usage: crate::lightning::routing::scoring::ChannelUsage, score_params: &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64,
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 ScoreLookUp {}
91 unsafe impl Sync for ScoreLookUp {}
93 pub(crate) fn ScoreLookUp_clone_fields(orig: &ScoreLookUp) -> ScoreLookUp {
95 this_arg: orig.this_arg,
96 channel_penalty_msat: Clone::clone(&orig.channel_penalty_msat),
97 free: Clone::clone(&orig.free),
101 use lightning::routing::scoring::ScoreLookUp as rustScoreLookUp;
102 impl rustScoreLookUp for ScoreLookUp {
103 fn channel_penalty_msat(&self, mut short_channel_id: u64, mut source: &lightning::routing::gossip::NodeId, mut target: &lightning::routing::gossip::NodeId, mut usage: lightning::routing::scoring::ChannelUsage, mut score_params: &lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
104 let mut ret = (self.channel_penalty_msat)(self.this_arg, short_channel_id, &crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((source as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false }, &crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((target as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false }, crate::lightning::routing::scoring::ChannelUsage { inner: ObjOps::heap_alloc(usage), is_owned: true }, &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((score_params as *const lightning::routing::scoring::ProbabilisticScoringFeeParameters<>) as *mut _) }, is_owned: false });
109 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
110 // directly as a Deref trait in higher-level structs:
111 impl core::ops::Deref for ScoreLookUp {
113 fn deref(&self) -> &Self {
117 impl core::ops::DerefMut for ScoreLookUp {
118 fn deref_mut(&mut self) -> &mut Self {
122 /// Calls the free function if one is set
124 pub extern "C" fn ScoreLookUp_free(this_ptr: ScoreLookUp) { }
125 impl Drop for ScoreLookUp {
127 if let Some(f) = self.free {
132 /// `ScoreUpdate` is used to update the scorer's internal state after a payment attempt.
134 pub struct ScoreUpdate {
135 /// An opaque pointer which is passed to your function implementations as an argument.
136 /// This has no meaning in the LDK, and can be NULL or any other value.
137 pub this_arg: *mut c_void,
138 /// Handles updating channel penalties after failing to route through a channel.
139 pub payment_path_failed: extern "C" fn (this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, short_channel_id: u64),
140 /// Handles updating channel penalties after successfully routing along a path.
141 pub payment_path_successful: extern "C" fn (this_arg: *mut c_void, path: &crate::lightning::routing::router::Path),
142 /// Handles updating channel penalties after a probe over the given path failed.
143 pub probe_failed: extern "C" fn (this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, short_channel_id: u64),
144 /// Handles updating channel penalties after a probe over the given path succeeded.
145 pub probe_successful: extern "C" fn (this_arg: *mut c_void, path: &crate::lightning::routing::router::Path),
146 /// Frees any resources associated with this object given its this_arg pointer.
147 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
148 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
150 unsafe impl Send for ScoreUpdate {}
151 unsafe impl Sync for ScoreUpdate {}
153 pub(crate) fn ScoreUpdate_clone_fields(orig: &ScoreUpdate) -> ScoreUpdate {
155 this_arg: orig.this_arg,
156 payment_path_failed: Clone::clone(&orig.payment_path_failed),
157 payment_path_successful: Clone::clone(&orig.payment_path_successful),
158 probe_failed: Clone::clone(&orig.probe_failed),
159 probe_successful: Clone::clone(&orig.probe_successful),
160 free: Clone::clone(&orig.free),
164 use lightning::routing::scoring::ScoreUpdate as rustScoreUpdate;
165 impl rustScoreUpdate for ScoreUpdate {
166 fn payment_path_failed(&mut self, mut path: &lightning::routing::router::Path, mut short_channel_id: u64) {
167 (self.payment_path_failed)(self.this_arg, &crate::lightning::routing::router::Path { inner: unsafe { ObjOps::nonnull_ptr_to_inner((path as *const lightning::routing::router::Path<>) as *mut _) }, is_owned: false }, short_channel_id)
169 fn payment_path_successful(&mut self, mut path: &lightning::routing::router::Path) {
170 (self.payment_path_successful)(self.this_arg, &crate::lightning::routing::router::Path { inner: unsafe { ObjOps::nonnull_ptr_to_inner((path as *const lightning::routing::router::Path<>) as *mut _) }, is_owned: false })
172 fn probe_failed(&mut self, mut path: &lightning::routing::router::Path, mut short_channel_id: u64) {
173 (self.probe_failed)(self.this_arg, &crate::lightning::routing::router::Path { inner: unsafe { ObjOps::nonnull_ptr_to_inner((path as *const lightning::routing::router::Path<>) as *mut _) }, is_owned: false }, short_channel_id)
175 fn probe_successful(&mut self, mut path: &lightning::routing::router::Path) {
176 (self.probe_successful)(self.this_arg, &crate::lightning::routing::router::Path { inner: unsafe { ObjOps::nonnull_ptr_to_inner((path as *const lightning::routing::router::Path<>) as *mut _) }, is_owned: false })
180 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
181 // directly as a Deref trait in higher-level structs:
182 impl core::ops::Deref for ScoreUpdate {
184 fn deref(&self) -> &Self {
188 impl core::ops::DerefMut for ScoreUpdate {
189 fn deref_mut(&mut self) -> &mut Self {
193 /// Calls the free function if one is set
195 pub extern "C" fn ScoreUpdate_free(this_ptr: ScoreUpdate) { }
196 impl Drop for ScoreUpdate {
198 if let Some(f) = self.free {
203 /// A trait which can both lookup and update routing channel penalty scores.
205 /// This is used in places where both bounds are required and implemented for all types which
206 /// implement [`ScoreLookUp`] and [`ScoreUpdate`].
208 /// Bindings users may need to manually implement this for their custom scoring implementations.
211 /// An opaque pointer which is passed to your function implementations as an argument.
212 /// This has no meaning in the LDK, and can be NULL or any other value.
213 pub this_arg: *mut c_void,
214 /// Implementation of ScoreLookUp for this object.
215 pub ScoreLookUp: crate::lightning::routing::scoring::ScoreLookUp,
216 /// Implementation of ScoreUpdate for this object.
217 pub ScoreUpdate: crate::lightning::routing::scoring::ScoreUpdate,
218 /// Serialize the object into a byte array
219 pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
220 /// Frees any resources associated with this object given its this_arg pointer.
221 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
222 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
224 unsafe impl Send for Score {}
225 unsafe impl Sync for Score {}
227 pub(crate) fn Score_clone_fields(orig: &Score) -> Score {
229 this_arg: orig.this_arg,
230 ScoreLookUp: crate::lightning::routing::scoring::ScoreLookUp_clone_fields(&orig.ScoreLookUp),
231 ScoreUpdate: crate::lightning::routing::scoring::ScoreUpdate_clone_fields(&orig.ScoreUpdate),
232 write: Clone::clone(&orig.write),
233 free: Clone::clone(&orig.free),
236 impl lightning::routing::scoring::ScoreLookUp for Score {
237 fn channel_penalty_msat(&self, mut short_channel_id: u64, mut source: &lightning::routing::gossip::NodeId, mut target: &lightning::routing::gossip::NodeId, mut usage: lightning::routing::scoring::ChannelUsage, mut score_params: &lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
238 let mut ret = (self.ScoreLookUp.channel_penalty_msat)(self.ScoreLookUp.this_arg, short_channel_id, &crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((source as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false }, &crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((target as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false }, crate::lightning::routing::scoring::ChannelUsage { inner: ObjOps::heap_alloc(usage), is_owned: true }, &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((score_params as *const lightning::routing::scoring::ProbabilisticScoringFeeParameters<>) as *mut _) }, is_owned: false });
242 impl lightning::routing::scoring::ScoreUpdate for Score {
243 fn payment_path_failed(&mut self, mut path: &lightning::routing::router::Path, mut short_channel_id: u64) {
244 (self.ScoreUpdate.payment_path_failed)(self.ScoreUpdate.this_arg, &crate::lightning::routing::router::Path { inner: unsafe { ObjOps::nonnull_ptr_to_inner((path as *const lightning::routing::router::Path<>) as *mut _) }, is_owned: false }, short_channel_id)
246 fn payment_path_successful(&mut self, mut path: &lightning::routing::router::Path) {
247 (self.ScoreUpdate.payment_path_successful)(self.ScoreUpdate.this_arg, &crate::lightning::routing::router::Path { inner: unsafe { ObjOps::nonnull_ptr_to_inner((path as *const lightning::routing::router::Path<>) as *mut _) }, is_owned: false })
249 fn probe_failed(&mut self, mut path: &lightning::routing::router::Path, mut short_channel_id: u64) {
250 (self.ScoreUpdate.probe_failed)(self.ScoreUpdate.this_arg, &crate::lightning::routing::router::Path { inner: unsafe { ObjOps::nonnull_ptr_to_inner((path as *const lightning::routing::router::Path<>) as *mut _) }, is_owned: false }, short_channel_id)
252 fn probe_successful(&mut self, mut path: &lightning::routing::router::Path) {
253 (self.ScoreUpdate.probe_successful)(self.ScoreUpdate.this_arg, &crate::lightning::routing::router::Path { inner: unsafe { ObjOps::nonnull_ptr_to_inner((path as *const lightning::routing::router::Path<>) as *mut _) }, is_owned: false })
256 impl lightning::util::ser::Writeable for Score {
257 fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
258 let vec = (self.write)(self.this_arg);
259 w.write_all(vec.as_slice())
263 use lightning::routing::scoring::Score as rustScore;
264 impl rustScore for Score {
267 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
268 // directly as a Deref trait in higher-level structs:
269 impl core::ops::Deref for Score {
271 fn deref(&self) -> &Self {
275 impl core::ops::DerefMut for Score {
276 fn deref_mut(&mut self) -> &mut Self {
280 /// Calls the free function if one is set
282 pub extern "C" fn Score_free(this_ptr: Score) { }
283 impl Drop for Score {
285 if let Some(f) = self.free {
290 /// A scorer that is accessed under a lock.
292 /// Needed so that calls to [`ScoreLookUp::channel_penalty_msat`] in [`find_route`] can be made while
293 /// having shared ownership of a scorer but without requiring internal locking in [`ScoreUpdate`]
294 /// implementations. Internal locking would be detrimental to route finding performance and could
295 /// result in [`ScoreLookUp::channel_penalty_msat`] returning a different value for the same channel.
297 /// [`find_route`]: crate::routing::router::find_route
299 pub struct LockableScore {
300 /// An opaque pointer which is passed to your function implementations as an argument.
301 /// This has no meaning in the LDK, and can be NULL or any other value.
302 pub this_arg: *mut c_void,
303 /// Returns read locked scorer.
304 pub read_lock: extern "C" fn (this_arg: *const c_void) -> crate::lightning::routing::scoring::ScoreLookUp,
305 /// Returns write locked scorer.
306 pub write_lock: extern "C" fn (this_arg: *const c_void) -> crate::lightning::routing::scoring::ScoreUpdate,
307 /// Frees any resources associated with this object given its this_arg pointer.
308 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
309 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
311 unsafe impl Send for LockableScore {}
312 unsafe impl Sync for LockableScore {}
314 pub(crate) fn LockableScore_clone_fields(orig: &LockableScore) -> LockableScore {
316 this_arg: orig.this_arg,
317 read_lock: Clone::clone(&orig.read_lock),
318 write_lock: Clone::clone(&orig.write_lock),
319 free: Clone::clone(&orig.free),
323 use lightning::routing::scoring::LockableScore as rustLockableScore;
324 impl<'a> rustLockableScore<'a> for LockableScore {
325 type ScoreUpdate = crate::lightning::routing::scoring::ScoreUpdate;
326 type ScoreLookUp = crate::lightning::routing::scoring::ScoreLookUp;
327 type WriteLocked = crate::lightning::routing::scoring::ScoreUpdate;
328 type ReadLocked = crate::lightning::routing::scoring::ScoreLookUp;
329 fn read_lock(&'a self) -> crate::lightning::routing::scoring::ScoreLookUp {
330 let mut ret = (self.read_lock)(self.this_arg);
333 fn write_lock(&'a self) -> crate::lightning::routing::scoring::ScoreUpdate {
334 let mut ret = (self.write_lock)(self.this_arg);
339 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
340 // directly as a Deref trait in higher-level structs:
341 impl core::ops::Deref for LockableScore {
343 fn deref(&self) -> &Self {
347 impl core::ops::DerefMut for LockableScore {
348 fn deref_mut(&mut self) -> &mut Self {
352 /// Calls the free function if one is set
354 pub extern "C" fn LockableScore_free(this_ptr: LockableScore) { }
355 impl Drop for LockableScore {
357 if let Some(f) = self.free {
362 /// Refers to a scorer that is accessible under lock and also writeable to disk
364 /// We need this trait to be able to pass in a scorer to `lightning-background-processor` that will enable us to
365 /// use the Persister to persist it.
367 pub struct WriteableScore {
368 /// An opaque pointer which is passed to your function implementations as an argument.
369 /// This has no meaning in the LDK, and can be NULL or any other value.
370 pub this_arg: *mut c_void,
371 /// Implementation of LockableScore for this object.
372 pub LockableScore: crate::lightning::routing::scoring::LockableScore,
373 /// Serialize the object into a byte array
374 pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
375 /// Frees any resources associated with this object given its this_arg pointer.
376 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
377 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
379 unsafe impl Send for WriteableScore {}
380 unsafe impl Sync for WriteableScore {}
382 pub(crate) fn WriteableScore_clone_fields(orig: &WriteableScore) -> WriteableScore {
384 this_arg: orig.this_arg,
385 LockableScore: crate::lightning::routing::scoring::LockableScore_clone_fields(&orig.LockableScore),
386 write: Clone::clone(&orig.write),
387 free: Clone::clone(&orig.free),
390 impl<'a> lightning::routing::scoring::LockableScore<'a> for WriteableScore {
391 type ScoreUpdate = crate::lightning::routing::scoring::ScoreUpdate;
392 type ScoreLookUp = crate::lightning::routing::scoring::ScoreLookUp;
393 type WriteLocked = crate::lightning::routing::scoring::ScoreUpdate;
394 type ReadLocked = crate::lightning::routing::scoring::ScoreLookUp;
395 fn read_lock(&'a self) -> crate::lightning::routing::scoring::ScoreLookUp {
396 let mut ret = (self.LockableScore.read_lock)(self.LockableScore.this_arg);
399 fn write_lock(&'a self) -> crate::lightning::routing::scoring::ScoreUpdate {
400 let mut ret = (self.LockableScore.write_lock)(self.LockableScore.this_arg);
404 impl lightning::util::ser::Writeable for WriteableScore {
405 fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
406 let vec = (self.write)(self.this_arg);
407 w.write_all(vec.as_slice())
411 use lightning::routing::scoring::WriteableScore as rustWriteableScore;
412 impl<'a> rustWriteableScore<'a> for WriteableScore {
415 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
416 // directly as a Deref trait in higher-level structs:
417 impl core::ops::Deref for WriteableScore {
419 fn deref(&self) -> &Self {
423 impl core::ops::DerefMut for WriteableScore {
424 fn deref_mut(&mut self) -> &mut Self {
428 /// Calls the free function if one is set
430 pub extern "C" fn WriteableScore_free(this_ptr: WriteableScore) { }
431 impl Drop for WriteableScore {
433 if let Some(f) = self.free {
439 use lightning::routing::scoring::MultiThreadedLockableScore as nativeMultiThreadedLockableScoreImport;
440 pub(crate) type nativeMultiThreadedLockableScore = nativeMultiThreadedLockableScoreImport<crate::lightning::routing::scoring::Score>;
442 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
445 pub struct MultiThreadedLockableScore {
446 /// A pointer to the opaque Rust object.
448 /// Nearly everywhere, inner must be non-null, however in places where
449 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
450 pub inner: *mut nativeMultiThreadedLockableScore,
451 /// Indicates that this is the only struct which contains the same pointer.
453 /// Rust functions which take ownership of an object provided via an argument require
454 /// this to be true and invalidate the object pointed to by inner.
458 impl Drop for MultiThreadedLockableScore {
460 if self.is_owned && !<*mut nativeMultiThreadedLockableScore>::is_null(self.inner) {
461 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
465 /// Frees any resources used by the MultiThreadedLockableScore, if is_owned is set and inner is non-NULL.
467 pub extern "C" fn MultiThreadedLockableScore_free(this_obj: MultiThreadedLockableScore) { }
469 /// Used only if an object of this type is returned as a trait impl by a method
470 pub(crate) extern "C" fn MultiThreadedLockableScore_free_void(this_ptr: *mut c_void) {
471 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeMultiThreadedLockableScore) };
474 impl MultiThreadedLockableScore {
475 pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedLockableScore {
476 unsafe { &*ObjOps::untweak_ptr(self.inner) }
478 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedLockableScore {
479 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
481 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
482 pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedLockableScore {
483 assert!(self.is_owned);
484 let ret = ObjOps::untweak_ptr(self.inner);
485 self.inner = core::ptr::null_mut();
489 impl From<nativeMultiThreadedLockableScore> for crate::lightning::routing::scoring::LockableScore {
490 fn from(obj: nativeMultiThreadedLockableScore) -> Self {
491 let rust_obj = crate::lightning::routing::scoring::MultiThreadedLockableScore { inner: ObjOps::heap_alloc(obj), is_owned: true };
492 let mut ret = MultiThreadedLockableScore_as_LockableScore(&rust_obj);
493 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
494 core::mem::forget(rust_obj);
495 ret.free = Some(MultiThreadedLockableScore_free_void);
499 /// Constructs a new LockableScore which calls the relevant methods on this_arg.
500 /// This copies the `inner` pointer in this_arg and thus the returned LockableScore must be freed before this_arg is
502 pub extern "C" fn MultiThreadedLockableScore_as_LockableScore(this_arg: &MultiThreadedLockableScore) -> crate::lightning::routing::scoring::LockableScore {
503 crate::lightning::routing::scoring::LockableScore {
504 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
506 read_lock: MultiThreadedLockableScore_LockableScore_read_lock,
507 write_lock: MultiThreadedLockableScore_LockableScore_write_lock,
512 extern "C" fn MultiThreadedLockableScore_LockableScore_read_lock(this_arg: *const c_void) -> crate::lightning::routing::scoring::ScoreLookUp {
513 let mut ret = <nativeMultiThreadedLockableScore as lightning::routing::scoring::LockableScore<>>::read_lock(unsafe { &mut *(this_arg as *mut nativeMultiThreadedLockableScore) }, );
517 extern "C" fn MultiThreadedLockableScore_LockableScore_write_lock(this_arg: *const c_void) -> crate::lightning::routing::scoring::ScoreUpdate {
518 let mut ret = <nativeMultiThreadedLockableScore as lightning::routing::scoring::LockableScore<>>::write_lock(unsafe { &mut *(this_arg as *mut nativeMultiThreadedLockableScore) }, );
523 /// Serialize the MultiThreadedLockableScore object into a byte array which can be read by MultiThreadedLockableScore_read
524 pub extern "C" fn MultiThreadedLockableScore_write(obj: &crate::lightning::routing::scoring::MultiThreadedLockableScore) -> crate::c_types::derived::CVec_u8Z {
525 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
528 pub(crate) extern "C" fn MultiThreadedLockableScore_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
529 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeMultiThreadedLockableScore) })
531 impl From<nativeMultiThreadedLockableScore> for crate::lightning::routing::scoring::WriteableScore {
532 fn from(obj: nativeMultiThreadedLockableScore) -> Self {
533 let rust_obj = crate::lightning::routing::scoring::MultiThreadedLockableScore { inner: ObjOps::heap_alloc(obj), is_owned: true };
534 let mut ret = MultiThreadedLockableScore_as_WriteableScore(&rust_obj);
535 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
536 core::mem::forget(rust_obj);
537 ret.free = Some(MultiThreadedLockableScore_free_void);
541 /// Constructs a new WriteableScore which calls the relevant methods on this_arg.
542 /// This copies the `inner` pointer in this_arg and thus the returned WriteableScore must be freed before this_arg is
544 pub extern "C" fn MultiThreadedLockableScore_as_WriteableScore(this_arg: &MultiThreadedLockableScore) -> crate::lightning::routing::scoring::WriteableScore {
545 crate::lightning::routing::scoring::WriteableScore {
546 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
548 LockableScore: crate::lightning::routing::scoring::LockableScore {
549 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
551 read_lock: MultiThreadedLockableScore_LockableScore_read_lock,
552 write_lock: MultiThreadedLockableScore_LockableScore_write_lock,
554 write: MultiThreadedLockableScore_write_void,
559 /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
562 pub extern "C" fn MultiThreadedLockableScore_new(mut score: crate::lightning::routing::scoring::Score) -> crate::lightning::routing::scoring::MultiThreadedLockableScore {
563 let mut ret = lightning::routing::scoring::MultiThreadedLockableScore::new(score);
564 crate::lightning::routing::scoring::MultiThreadedLockableScore { inner: ObjOps::heap_alloc(ret), is_owned: true }
568 use lightning::routing::scoring::MultiThreadedScoreLockRead as nativeMultiThreadedScoreLockReadImport;
569 pub(crate) type nativeMultiThreadedScoreLockRead = nativeMultiThreadedScoreLockReadImport<'static, crate::lightning::routing::scoring::Score>;
571 /// A locked `MultiThreadedLockableScore`.
574 pub struct MultiThreadedScoreLockRead {
575 /// A pointer to the opaque Rust object.
577 /// Nearly everywhere, inner must be non-null, however in places where
578 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
579 pub inner: *mut nativeMultiThreadedScoreLockRead,
580 /// Indicates that this is the only struct which contains the same pointer.
582 /// Rust functions which take ownership of an object provided via an argument require
583 /// this to be true and invalidate the object pointed to by inner.
587 impl Drop for MultiThreadedScoreLockRead {
589 if self.is_owned && !<*mut nativeMultiThreadedScoreLockRead>::is_null(self.inner) {
590 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
594 /// Frees any resources used by the MultiThreadedScoreLockRead, if is_owned is set and inner is non-NULL.
596 pub extern "C" fn MultiThreadedScoreLockRead_free(this_obj: MultiThreadedScoreLockRead) { }
598 /// Used only if an object of this type is returned as a trait impl by a method
599 pub(crate) extern "C" fn MultiThreadedScoreLockRead_free_void(this_ptr: *mut c_void) {
600 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeMultiThreadedScoreLockRead) };
603 impl MultiThreadedScoreLockRead {
604 pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedScoreLockRead {
605 unsafe { &*ObjOps::untweak_ptr(self.inner) }
607 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedScoreLockRead {
608 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
610 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
611 pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedScoreLockRead {
612 assert!(self.is_owned);
613 let ret = ObjOps::untweak_ptr(self.inner);
614 self.inner = core::ptr::null_mut();
619 use lightning::routing::scoring::MultiThreadedScoreLockWrite as nativeMultiThreadedScoreLockWriteImport;
620 pub(crate) type nativeMultiThreadedScoreLockWrite = nativeMultiThreadedScoreLockWriteImport<'static, crate::lightning::routing::scoring::Score>;
622 /// A locked `MultiThreadedLockableScore`.
625 pub struct MultiThreadedScoreLockWrite {
626 /// A pointer to the opaque Rust object.
628 /// Nearly everywhere, inner must be non-null, however in places where
629 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
630 pub inner: *mut nativeMultiThreadedScoreLockWrite,
631 /// Indicates that this is the only struct which contains the same pointer.
633 /// Rust functions which take ownership of an object provided via an argument require
634 /// this to be true and invalidate the object pointed to by inner.
638 impl Drop for MultiThreadedScoreLockWrite {
640 if self.is_owned && !<*mut nativeMultiThreadedScoreLockWrite>::is_null(self.inner) {
641 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
645 /// Frees any resources used by the MultiThreadedScoreLockWrite, if is_owned is set and inner is non-NULL.
647 pub extern "C" fn MultiThreadedScoreLockWrite_free(this_obj: MultiThreadedScoreLockWrite) { }
649 /// Used only if an object of this type is returned as a trait impl by a method
650 pub(crate) extern "C" fn MultiThreadedScoreLockWrite_free_void(this_ptr: *mut c_void) {
651 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeMultiThreadedScoreLockWrite) };
654 impl MultiThreadedScoreLockWrite {
655 pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedScoreLockWrite {
656 unsafe { &*ObjOps::untweak_ptr(self.inner) }
658 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedScoreLockWrite {
659 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
661 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
662 pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedScoreLockWrite {
663 assert!(self.is_owned);
664 let ret = ObjOps::untweak_ptr(self.inner);
665 self.inner = core::ptr::null_mut();
669 impl From<nativeMultiThreadedScoreLockRead> for crate::lightning::routing::scoring::ScoreLookUp {
670 fn from(obj: nativeMultiThreadedScoreLockRead) -> Self {
671 let rust_obj = crate::lightning::routing::scoring::MultiThreadedScoreLockRead { inner: ObjOps::heap_alloc(obj), is_owned: true };
672 let mut ret = MultiThreadedScoreLockRead_as_ScoreLookUp(&rust_obj);
673 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
674 core::mem::forget(rust_obj);
675 ret.free = Some(MultiThreadedScoreLockRead_free_void);
679 /// Constructs a new ScoreLookUp which calls the relevant methods on this_arg.
680 /// This copies the `inner` pointer in this_arg and thus the returned ScoreLookUp must be freed before this_arg is
682 pub extern "C" fn MultiThreadedScoreLockRead_as_ScoreLookUp(this_arg: &MultiThreadedScoreLockRead) -> crate::lightning::routing::scoring::ScoreLookUp {
683 crate::lightning::routing::scoring::ScoreLookUp {
684 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
686 channel_penalty_msat: MultiThreadedScoreLockRead_ScoreLookUp_channel_penalty_msat,
691 extern "C" fn MultiThreadedScoreLockRead_ScoreLookUp_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, mut usage: crate::lightning::routing::scoring::ChannelUsage, score_params: &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
692 let mut ret = <nativeMultiThreadedScoreLockRead as lightning::routing::scoring::ScoreLookUp<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLockRead) }, short_channel_id, source.get_native_ref(), target.get_native_ref(), *unsafe { Box::from_raw(usage.take_inner()) }, score_params.get_native_ref());
697 /// Serialize the MultiThreadedScoreLockWrite object into a byte array which can be read by MultiThreadedScoreLockWrite_read
698 pub extern "C" fn MultiThreadedScoreLockWrite_write(obj: &crate::lightning::routing::scoring::MultiThreadedScoreLockWrite) -> crate::c_types::derived::CVec_u8Z {
699 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
702 pub(crate) extern "C" fn MultiThreadedScoreLockWrite_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
703 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeMultiThreadedScoreLockWrite) })
705 impl From<nativeMultiThreadedScoreLockWrite> for crate::lightning::routing::scoring::ScoreUpdate {
706 fn from(obj: nativeMultiThreadedScoreLockWrite) -> Self {
707 let rust_obj = crate::lightning::routing::scoring::MultiThreadedScoreLockWrite { inner: ObjOps::heap_alloc(obj), is_owned: true };
708 let mut ret = MultiThreadedScoreLockWrite_as_ScoreUpdate(&rust_obj);
709 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
710 core::mem::forget(rust_obj);
711 ret.free = Some(MultiThreadedScoreLockWrite_free_void);
715 /// Constructs a new ScoreUpdate which calls the relevant methods on this_arg.
716 /// This copies the `inner` pointer in this_arg and thus the returned ScoreUpdate must be freed before this_arg is
718 pub extern "C" fn MultiThreadedScoreLockWrite_as_ScoreUpdate(this_arg: &MultiThreadedScoreLockWrite) -> crate::lightning::routing::scoring::ScoreUpdate {
719 crate::lightning::routing::scoring::ScoreUpdate {
720 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
722 payment_path_failed: MultiThreadedScoreLockWrite_ScoreUpdate_payment_path_failed,
723 payment_path_successful: MultiThreadedScoreLockWrite_ScoreUpdate_payment_path_successful,
724 probe_failed: MultiThreadedScoreLockWrite_ScoreUpdate_probe_failed,
725 probe_successful: MultiThreadedScoreLockWrite_ScoreUpdate_probe_successful,
729 extern "C" fn MultiThreadedScoreLockWrite_ScoreUpdate_payment_path_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
730 <nativeMultiThreadedScoreLockWrite as lightning::routing::scoring::ScoreUpdate<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLockWrite) }, path.get_native_ref(), short_channel_id)
732 extern "C" fn MultiThreadedScoreLockWrite_ScoreUpdate_payment_path_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
733 <nativeMultiThreadedScoreLockWrite as lightning::routing::scoring::ScoreUpdate<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLockWrite) }, path.get_native_ref())
735 extern "C" fn MultiThreadedScoreLockWrite_ScoreUpdate_probe_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
736 <nativeMultiThreadedScoreLockWrite as lightning::routing::scoring::ScoreUpdate<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLockWrite) }, path.get_native_ref(), short_channel_id)
738 extern "C" fn MultiThreadedScoreLockWrite_ScoreUpdate_probe_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
739 <nativeMultiThreadedScoreLockWrite as lightning::routing::scoring::ScoreUpdate<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLockWrite) }, path.get_native_ref())
743 use lightning::routing::scoring::ChannelUsage as nativeChannelUsageImport;
744 pub(crate) type nativeChannelUsage = nativeChannelUsageImport;
746 /// Proposed use of a channel passed as a parameter to [`ScoreLookUp::channel_penalty_msat`].
749 pub struct ChannelUsage {
750 /// A pointer to the opaque Rust object.
752 /// Nearly everywhere, inner must be non-null, however in places where
753 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
754 pub inner: *mut nativeChannelUsage,
755 /// Indicates that this is the only struct which contains the same pointer.
757 /// Rust functions which take ownership of an object provided via an argument require
758 /// this to be true and invalidate the object pointed to by inner.
762 impl Drop for ChannelUsage {
764 if self.is_owned && !<*mut nativeChannelUsage>::is_null(self.inner) {
765 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
769 /// Frees any resources used by the ChannelUsage, if is_owned is set and inner is non-NULL.
771 pub extern "C" fn ChannelUsage_free(this_obj: ChannelUsage) { }
773 /// Used only if an object of this type is returned as a trait impl by a method
774 pub(crate) extern "C" fn ChannelUsage_free_void(this_ptr: *mut c_void) {
775 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChannelUsage) };
779 pub(crate) fn get_native_ref(&self) -> &'static nativeChannelUsage {
780 unsafe { &*ObjOps::untweak_ptr(self.inner) }
782 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelUsage {
783 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
785 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
786 pub(crate) fn take_inner(mut self) -> *mut nativeChannelUsage {
787 assert!(self.is_owned);
788 let ret = ObjOps::untweak_ptr(self.inner);
789 self.inner = core::ptr::null_mut();
793 /// The amount to send through the channel, denominated in millisatoshis.
795 pub extern "C" fn ChannelUsage_get_amount_msat(this_ptr: &ChannelUsage) -> u64 {
796 let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_msat;
799 /// The amount to send through the channel, denominated in millisatoshis.
801 pub extern "C" fn ChannelUsage_set_amount_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
802 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_msat = val;
804 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
805 /// as part of a multi-path payment.
807 pub extern "C" fn ChannelUsage_get_inflight_htlc_msat(this_ptr: &ChannelUsage) -> u64 {
808 let mut inner_val = &mut this_ptr.get_native_mut_ref().inflight_htlc_msat;
811 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
812 /// as part of a multi-path payment.
814 pub extern "C" fn ChannelUsage_set_inflight_htlc_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
815 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inflight_htlc_msat = val;
817 /// The effective capacity of the channel.
819 pub extern "C" fn ChannelUsage_get_effective_capacity(this_ptr: &ChannelUsage) -> crate::lightning::routing::gossip::EffectiveCapacity {
820 let mut inner_val = &mut this_ptr.get_native_mut_ref().effective_capacity;
821 crate::lightning::routing::gossip::EffectiveCapacity::from_native(inner_val)
823 /// The effective capacity of the channel.
825 pub extern "C" fn ChannelUsage_set_effective_capacity(this_ptr: &mut ChannelUsage, mut val: crate::lightning::routing::gossip::EffectiveCapacity) {
826 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.effective_capacity = val.into_native();
828 /// Constructs a new ChannelUsage given each field
831 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 {
832 ChannelUsage { inner: ObjOps::heap_alloc(nativeChannelUsage {
833 amount_msat: amount_msat_arg,
834 inflight_htlc_msat: inflight_htlc_msat_arg,
835 effective_capacity: effective_capacity_arg.into_native(),
838 impl Clone for ChannelUsage {
839 fn clone(&self) -> Self {
841 inner: if <*mut nativeChannelUsage>::is_null(self.inner) { core::ptr::null_mut() } else {
842 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
848 /// Used only if an object of this type is returned as a trait impl by a method
849 pub(crate) extern "C" fn ChannelUsage_clone_void(this_ptr: *const c_void) -> *mut c_void {
850 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeChannelUsage)).clone() })) as *mut c_void
853 /// Creates a copy of the ChannelUsage
854 pub extern "C" fn ChannelUsage_clone(orig: &ChannelUsage) -> ChannelUsage {
858 use lightning::routing::scoring::FixedPenaltyScorer as nativeFixedPenaltyScorerImport;
859 pub(crate) type nativeFixedPenaltyScorer = nativeFixedPenaltyScorerImport;
861 /// [`ScoreLookUp`] implementation that uses a fixed penalty.
864 pub struct FixedPenaltyScorer {
865 /// A pointer to the opaque Rust object.
867 /// Nearly everywhere, inner must be non-null, however in places where
868 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
869 pub inner: *mut nativeFixedPenaltyScorer,
870 /// Indicates that this is the only struct which contains the same pointer.
872 /// Rust functions which take ownership of an object provided via an argument require
873 /// this to be true and invalidate the object pointed to by inner.
877 impl Drop for FixedPenaltyScorer {
879 if self.is_owned && !<*mut nativeFixedPenaltyScorer>::is_null(self.inner) {
880 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
884 /// Frees any resources used by the FixedPenaltyScorer, if is_owned is set and inner is non-NULL.
886 pub extern "C" fn FixedPenaltyScorer_free(this_obj: FixedPenaltyScorer) { }
888 /// Used only if an object of this type is returned as a trait impl by a method
889 pub(crate) extern "C" fn FixedPenaltyScorer_free_void(this_ptr: *mut c_void) {
890 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeFixedPenaltyScorer) };
893 impl FixedPenaltyScorer {
894 pub(crate) fn get_native_ref(&self) -> &'static nativeFixedPenaltyScorer {
895 unsafe { &*ObjOps::untweak_ptr(self.inner) }
897 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFixedPenaltyScorer {
898 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
900 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
901 pub(crate) fn take_inner(mut self) -> *mut nativeFixedPenaltyScorer {
902 assert!(self.is_owned);
903 let ret = ObjOps::untweak_ptr(self.inner);
904 self.inner = core::ptr::null_mut();
908 impl Clone for FixedPenaltyScorer {
909 fn clone(&self) -> Self {
911 inner: if <*mut nativeFixedPenaltyScorer>::is_null(self.inner) { core::ptr::null_mut() } else {
912 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
918 /// Used only if an object of this type is returned as a trait impl by a method
919 pub(crate) extern "C" fn FixedPenaltyScorer_clone_void(this_ptr: *const c_void) -> *mut c_void {
920 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeFixedPenaltyScorer)).clone() })) as *mut c_void
923 /// Creates a copy of the FixedPenaltyScorer
924 pub extern "C" fn FixedPenaltyScorer_clone(orig: &FixedPenaltyScorer) -> FixedPenaltyScorer {
927 /// Creates a new scorer using `penalty_msat`.
930 pub extern "C" fn FixedPenaltyScorer_with_penalty(mut penalty_msat: u64) -> crate::lightning::routing::scoring::FixedPenaltyScorer {
931 let mut ret = lightning::routing::scoring::FixedPenaltyScorer::with_penalty(penalty_msat);
932 crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
935 impl From<nativeFixedPenaltyScorer> for crate::lightning::routing::scoring::ScoreLookUp {
936 fn from(obj: nativeFixedPenaltyScorer) -> Self {
937 let rust_obj = crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
938 let mut ret = FixedPenaltyScorer_as_ScoreLookUp(&rust_obj);
939 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
940 core::mem::forget(rust_obj);
941 ret.free = Some(FixedPenaltyScorer_free_void);
945 /// Constructs a new ScoreLookUp which calls the relevant methods on this_arg.
946 /// This copies the `inner` pointer in this_arg and thus the returned ScoreLookUp must be freed before this_arg is
948 pub extern "C" fn FixedPenaltyScorer_as_ScoreLookUp(this_arg: &FixedPenaltyScorer) -> crate::lightning::routing::scoring::ScoreLookUp {
949 crate::lightning::routing::scoring::ScoreLookUp {
950 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
952 channel_penalty_msat: FixedPenaltyScorer_ScoreLookUp_channel_penalty_msat,
957 extern "C" fn FixedPenaltyScorer_ScoreLookUp_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, mut usage: crate::lightning::routing::scoring::ChannelUsage, score_params: &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
958 let mut ret = <nativeFixedPenaltyScorer as lightning::routing::scoring::ScoreLookUp<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, short_channel_id, source.get_native_ref(), target.get_native_ref(), *unsafe { Box::from_raw(usage.take_inner()) }, score_params.get_native_ref());
962 impl From<nativeFixedPenaltyScorer> for crate::lightning::routing::scoring::ScoreUpdate {
963 fn from(obj: nativeFixedPenaltyScorer) -> Self {
964 let rust_obj = crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
965 let mut ret = FixedPenaltyScorer_as_ScoreUpdate(&rust_obj);
966 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
967 core::mem::forget(rust_obj);
968 ret.free = Some(FixedPenaltyScorer_free_void);
972 /// Constructs a new ScoreUpdate which calls the relevant methods on this_arg.
973 /// This copies the `inner` pointer in this_arg and thus the returned ScoreUpdate must be freed before this_arg is
975 pub extern "C" fn FixedPenaltyScorer_as_ScoreUpdate(this_arg: &FixedPenaltyScorer) -> crate::lightning::routing::scoring::ScoreUpdate {
976 crate::lightning::routing::scoring::ScoreUpdate {
977 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
979 payment_path_failed: FixedPenaltyScorer_ScoreUpdate_payment_path_failed,
980 payment_path_successful: FixedPenaltyScorer_ScoreUpdate_payment_path_successful,
981 probe_failed: FixedPenaltyScorer_ScoreUpdate_probe_failed,
982 probe_successful: FixedPenaltyScorer_ScoreUpdate_probe_successful,
986 extern "C" fn FixedPenaltyScorer_ScoreUpdate_payment_path_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
987 <nativeFixedPenaltyScorer as lightning::routing::scoring::ScoreUpdate<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref(), short_channel_id)
989 extern "C" fn FixedPenaltyScorer_ScoreUpdate_payment_path_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
990 <nativeFixedPenaltyScorer as lightning::routing::scoring::ScoreUpdate<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref())
992 extern "C" fn FixedPenaltyScorer_ScoreUpdate_probe_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
993 <nativeFixedPenaltyScorer as lightning::routing::scoring::ScoreUpdate<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref(), short_channel_id)
995 extern "C" fn FixedPenaltyScorer_ScoreUpdate_probe_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
996 <nativeFixedPenaltyScorer as lightning::routing::scoring::ScoreUpdate<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref())
1000 /// Serialize the FixedPenaltyScorer object into a byte array which can be read by FixedPenaltyScorer_read
1001 pub extern "C" fn FixedPenaltyScorer_write(obj: &crate::lightning::routing::scoring::FixedPenaltyScorer) -> crate::c_types::derived::CVec_u8Z {
1002 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
1005 pub(crate) extern "C" fn FixedPenaltyScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
1006 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFixedPenaltyScorer) })
1009 /// Read a FixedPenaltyScorer from a byte array, created by FixedPenaltyScorer_write
1010 pub extern "C" fn FixedPenaltyScorer_read(ser: crate::c_types::u8slice, arg: u64) -> crate::c_types::derived::CResult_FixedPenaltyScorerDecodeErrorZ {
1012 let res: Result<lightning::routing::scoring::FixedPenaltyScorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
1013 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() };
1017 use lightning::routing::scoring::ProbabilisticScorer as nativeProbabilisticScorerImport;
1018 pub(crate) type nativeProbabilisticScorer = nativeProbabilisticScorerImport<&'static lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger>;
1020 /// [`ScoreLookUp`] implementation using channel success probability distributions.
1022 /// Channels are tracked with upper and lower liquidity bounds - when an HTLC fails at a channel,
1023 /// we learn that the upper-bound on the available liquidity is lower than the amount of the HTLC.
1024 /// When a payment is forwarded through a channel (but fails later in the route), we learn the
1025 /// lower-bound on the channel's available liquidity must be at least the value of the HTLC.
1027 /// These bounds are then used to determine a success probability using the formula from
1028 /// *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
1029 /// and Stefan Richter [[1]] (i.e. `(upper_bound - payment_amount) / (upper_bound - lower_bound)`).
1031 /// This probability is combined with the [`liquidity_penalty_multiplier_msat`] and
1032 /// [`liquidity_penalty_amount_multiplier_msat`] parameters to calculate a concrete penalty in
1033 /// milli-satoshis. The penalties, when added across all hops, have the property of being linear in
1034 /// terms of the entire path's success probability. This allows the router to directly compare
1035 /// penalties for different paths. See the documentation of those parameters for the exact formulas.
1037 /// The liquidity bounds are decayed by halving them every [`liquidity_offset_half_life`].
1039 /// Further, we track the history of our upper and lower liquidity bounds for each channel,
1040 /// allowing us to assign a second penalty (using [`historical_liquidity_penalty_multiplier_msat`]
1041 /// and [`historical_liquidity_penalty_amount_multiplier_msat`]) based on the same probability
1042 /// formula, but using the history of a channel rather than our latest estimates for the liquidity
1047 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
1050 /// [1]: https://arxiv.org/abs/2107.05322
1051 /// [`liquidity_penalty_multiplier_msat`]: ProbabilisticScoringFeeParameters::liquidity_penalty_multiplier_msat
1052 /// [`liquidity_penalty_amount_multiplier_msat`]: ProbabilisticScoringFeeParameters::liquidity_penalty_amount_multiplier_msat
1053 /// [`liquidity_offset_half_life`]: ProbabilisticScoringDecayParameters::liquidity_offset_half_life
1054 /// [`historical_liquidity_penalty_multiplier_msat`]: ProbabilisticScoringFeeParameters::historical_liquidity_penalty_multiplier_msat
1055 /// [`historical_liquidity_penalty_amount_multiplier_msat`]: ProbabilisticScoringFeeParameters::historical_liquidity_penalty_amount_multiplier_msat
1058 pub struct ProbabilisticScorer {
1059 /// A pointer to the opaque Rust object.
1061 /// Nearly everywhere, inner must be non-null, however in places where
1062 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
1063 pub inner: *mut nativeProbabilisticScorer,
1064 /// Indicates that this is the only struct which contains the same pointer.
1066 /// Rust functions which take ownership of an object provided via an argument require
1067 /// this to be true and invalidate the object pointed to by inner.
1071 impl Drop for ProbabilisticScorer {
1072 fn drop(&mut self) {
1073 if self.is_owned && !<*mut nativeProbabilisticScorer>::is_null(self.inner) {
1074 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
1078 /// Frees any resources used by the ProbabilisticScorer, if is_owned is set and inner is non-NULL.
1080 pub extern "C" fn ProbabilisticScorer_free(this_obj: ProbabilisticScorer) { }
1082 /// Used only if an object of this type is returned as a trait impl by a method
1083 pub(crate) extern "C" fn ProbabilisticScorer_free_void(this_ptr: *mut c_void) {
1084 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeProbabilisticScorer) };
1087 impl ProbabilisticScorer {
1088 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScorer {
1089 unsafe { &*ObjOps::untweak_ptr(self.inner) }
1091 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScorer {
1092 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
1094 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
1095 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScorer {
1096 assert!(self.is_owned);
1097 let ret = ObjOps::untweak_ptr(self.inner);
1098 self.inner = core::ptr::null_mut();
1103 use lightning::routing::scoring::ProbabilisticScoringFeeParameters as nativeProbabilisticScoringFeeParametersImport;
1104 pub(crate) type nativeProbabilisticScoringFeeParameters = nativeProbabilisticScoringFeeParametersImport;
1106 /// Parameters for configuring [`ProbabilisticScorer`].
1108 /// Used to configure base, liquidity, and amount penalties, the sum of which comprises the channel
1109 /// penalty (i.e., the amount in msats willing to be paid to avoid routing through the channel).
1111 /// The penalty applied to any channel by the [`ProbabilisticScorer`] is the sum of each of the
1112 /// parameters here.
1115 pub struct ProbabilisticScoringFeeParameters {
1116 /// A pointer to the opaque Rust object.
1118 /// Nearly everywhere, inner must be non-null, however in places where
1119 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
1120 pub inner: *mut nativeProbabilisticScoringFeeParameters,
1121 /// Indicates that this is the only struct which contains the same pointer.
1123 /// Rust functions which take ownership of an object provided via an argument require
1124 /// this to be true and invalidate the object pointed to by inner.
1128 impl Drop for ProbabilisticScoringFeeParameters {
1129 fn drop(&mut self) {
1130 if self.is_owned && !<*mut nativeProbabilisticScoringFeeParameters>::is_null(self.inner) {
1131 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
1135 /// Frees any resources used by the ProbabilisticScoringFeeParameters, if is_owned is set and inner is non-NULL.
1137 pub extern "C" fn ProbabilisticScoringFeeParameters_free(this_obj: ProbabilisticScoringFeeParameters) { }
1139 /// Used only if an object of this type is returned as a trait impl by a method
1140 pub(crate) extern "C" fn ProbabilisticScoringFeeParameters_free_void(this_ptr: *mut c_void) {
1141 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeProbabilisticScoringFeeParameters) };
1144 impl ProbabilisticScoringFeeParameters {
1145 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringFeeParameters {
1146 unsafe { &*ObjOps::untweak_ptr(self.inner) }
1148 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringFeeParameters {
1149 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
1151 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
1152 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringFeeParameters {
1153 assert!(self.is_owned);
1154 let ret = ObjOps::untweak_ptr(self.inner);
1155 self.inner = core::ptr::null_mut();
1159 /// A fixed penalty in msats to apply to each channel.
1161 /// Default value: 500 msat
1163 pub extern "C" fn ProbabilisticScoringFeeParameters_get_base_penalty_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1164 let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
1167 /// A fixed penalty in msats to apply to each channel.
1169 /// Default value: 500 msat
1171 pub extern "C" fn ProbabilisticScoringFeeParameters_set_base_penalty_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1172 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
1174 /// A multiplier used with the total amount flowing over a channel to calculate a fixed penalty
1175 /// applied to each channel, in excess of the [`base_penalty_msat`].
1177 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
1178 /// fees plus penalty) for large payments. The penalty is computed as the product of this
1179 /// multiplier and `2^30`ths of the total amount flowing over a channel (i.e. the payment
1180 /// amount plus the amount of any other HTLCs flowing we sent over the same channel).
1182 /// ie `base_penalty_amount_multiplier_msat * amount_msat / 2^30`
1184 /// Default value: 8,192 msat
1186 /// [`base_penalty_msat`]: Self::base_penalty_msat
1188 pub extern "C" fn ProbabilisticScoringFeeParameters_get_base_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1189 let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_amount_multiplier_msat;
1192 /// A multiplier used with the total amount flowing over a channel to calculate a fixed penalty
1193 /// applied to each channel, in excess of the [`base_penalty_msat`].
1195 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
1196 /// fees plus penalty) for large payments. The penalty is computed as the product of this
1197 /// multiplier and `2^30`ths of the total amount flowing over a channel (i.e. the payment
1198 /// amount plus the amount of any other HTLCs flowing we sent over the same channel).
1200 /// ie `base_penalty_amount_multiplier_msat * amount_msat / 2^30`
1202 /// Default value: 8,192 msat
1204 /// [`base_penalty_msat`]: Self::base_penalty_msat
1206 pub extern "C" fn ProbabilisticScoringFeeParameters_set_base_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1207 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_amount_multiplier_msat = val;
1209 /// A multiplier used in conjunction with the negative `log10` of the channel's success
1210 /// probability for a payment, as determined by our latest estimates of the channel's
1211 /// liquidity, to determine the liquidity penalty.
1213 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
1214 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
1215 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
1216 /// lower bounding the success probability to `0.01`) when the amount falls within the
1217 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
1218 /// result in a `u64::max_value` penalty, however.
1220 /// `-log10(success_probability) * liquidity_penalty_multiplier_msat`
1222 /// Default value: 30,000 msat
1224 /// [`liquidity_offset_half_life`]: ProbabilisticScoringDecayParameters::liquidity_offset_half_life
1226 pub extern "C" fn ProbabilisticScoringFeeParameters_get_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1227 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_multiplier_msat;
1230 /// A multiplier used in conjunction with the negative `log10` of the channel's success
1231 /// probability for a payment, as determined by our latest estimates of the channel's
1232 /// liquidity, to determine the liquidity penalty.
1234 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
1235 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
1236 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
1237 /// lower bounding the success probability to `0.01`) when the amount falls within the
1238 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
1239 /// result in a `u64::max_value` penalty, however.
1241 /// `-log10(success_probability) * liquidity_penalty_multiplier_msat`
1243 /// Default value: 30,000 msat
1245 /// [`liquidity_offset_half_life`]: ProbabilisticScoringDecayParameters::liquidity_offset_half_life
1247 pub extern "C" fn ProbabilisticScoringFeeParameters_set_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1248 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_multiplier_msat = val;
1250 /// A multiplier used in conjunction with the total amount flowing over a channel and the
1251 /// negative `log10` of the channel's success probability for the payment, as determined by our
1252 /// latest estimates of the channel's liquidity, to determine the amount penalty.
1254 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
1255 /// fees plus penalty) for large payments. The penalty is computed as the product of this
1256 /// multiplier and `2^20`ths of the amount flowing over this channel, weighted by the negative
1257 /// `log10` of the success probability.
1259 /// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
1261 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
1262 /// the amount will result in a penalty of the multiplier. And, as the success probability
1263 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
1264 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
1267 /// Default value: 192 msat
1269 pub extern "C" fn ProbabilisticScoringFeeParameters_get_liquidity_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1270 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_amount_multiplier_msat;
1273 /// A multiplier used in conjunction with the total amount flowing over a channel and the
1274 /// negative `log10` of the channel's success probability for the payment, as determined by our
1275 /// latest estimates of the channel's liquidity, to determine the amount penalty.
1277 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
1278 /// fees plus penalty) for large payments. The penalty is computed as the product of this
1279 /// multiplier and `2^20`ths of the amount flowing over this channel, weighted by the negative
1280 /// `log10` of the success probability.
1282 /// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
1284 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
1285 /// the amount will result in a penalty of the multiplier. And, as the success probability
1286 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
1287 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
1290 /// Default value: 192 msat
1292 pub extern "C" fn ProbabilisticScoringFeeParameters_set_liquidity_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1293 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_amount_multiplier_msat = val;
1295 /// A multiplier used in conjunction with the negative `log10` of the channel's success
1296 /// probability for the payment, as determined based on the history of our estimates of the
1297 /// channel's available liquidity, to determine a penalty.
1299 /// This penalty is similar to [`liquidity_penalty_multiplier_msat`], however, instead of using
1300 /// only our latest estimate for the current liquidity available in the channel, it estimates
1301 /// success probability based on the estimated liquidity available in the channel through
1302 /// history. Specifically, every time we update our liquidity bounds on a given channel, we
1303 /// track which of several buckets those bounds fall into, exponentially decaying the
1304 /// probability of each bucket as new samples are added.
1306 /// Default value: 10,000 msat
1308 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1310 pub extern "C" fn ProbabilisticScoringFeeParameters_get_historical_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1311 let mut inner_val = &mut this_ptr.get_native_mut_ref().historical_liquidity_penalty_multiplier_msat;
1314 /// A multiplier used in conjunction with the negative `log10` of the channel's success
1315 /// probability for the payment, as determined based on the history of our estimates of the
1316 /// channel's available liquidity, to determine a penalty.
1318 /// This penalty is similar to [`liquidity_penalty_multiplier_msat`], however, instead of using
1319 /// only our latest estimate for the current liquidity available in the channel, it estimates
1320 /// success probability based on the estimated liquidity available in the channel through
1321 /// history. Specifically, every time we update our liquidity bounds on a given channel, we
1322 /// track which of several buckets those bounds fall into, exponentially decaying the
1323 /// probability of each bucket as new samples are added.
1325 /// Default value: 10,000 msat
1327 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1329 pub extern "C" fn ProbabilisticScoringFeeParameters_set_historical_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1330 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.historical_liquidity_penalty_multiplier_msat = val;
1332 /// A multiplier used in conjunction with the total amount flowing over a channel and the
1333 /// negative `log10` of the channel's success probability for the payment, as determined based
1334 /// on the history of our estimates of the channel's available liquidity, to determine a
1337 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost for
1338 /// large payments. The penalty is computed as the product of this multiplier and `2^20`ths
1339 /// of the amount flowing over this channel, weighted by the negative `log10` of the success
1342 /// This penalty is similar to [`liquidity_penalty_amount_multiplier_msat`], however, instead
1343 /// of using only our latest estimate for the current liquidity available in the channel, it
1344 /// estimates success probability based on the estimated liquidity available in the channel
1345 /// through history. Specifically, every time we update our liquidity bounds on a given
1346 /// channel, we track which of several buckets those bounds fall into, exponentially decaying
1347 /// the probability of each bucket as new samples are added.
1349 /// Default value: 64 msat
1351 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1353 pub extern "C" fn ProbabilisticScoringFeeParameters_get_historical_liquidity_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1354 let mut inner_val = &mut this_ptr.get_native_mut_ref().historical_liquidity_penalty_amount_multiplier_msat;
1357 /// A multiplier used in conjunction with the total amount flowing over a channel and the
1358 /// negative `log10` of the channel's success probability for the payment, as determined based
1359 /// on the history of our estimates of the channel's available liquidity, to determine a
1362 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost for
1363 /// large payments. The penalty is computed as the product of this multiplier and `2^20`ths
1364 /// of the amount flowing over this channel, weighted by the negative `log10` of the success
1367 /// This penalty is similar to [`liquidity_penalty_amount_multiplier_msat`], however, instead
1368 /// of using only our latest estimate for the current liquidity available in the channel, it
1369 /// estimates success probability based on the estimated liquidity available in the channel
1370 /// through history. Specifically, every time we update our liquidity bounds on a given
1371 /// channel, we track which of several buckets those bounds fall into, exponentially decaying
1372 /// the probability of each bucket as new samples are added.
1374 /// Default value: 64 msat
1376 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1378 pub extern "C" fn ProbabilisticScoringFeeParameters_set_historical_liquidity_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1379 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.historical_liquidity_penalty_amount_multiplier_msat = val;
1381 /// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
1382 /// channel's capacity, (ie. htlc_maximum_msat >= 0.5 * channel_capacity) which makes us
1383 /// prefer nodes with a smaller `htlc_maximum_msat`. We treat such nodes preferentially
1384 /// as this makes balance discovery attacks harder to execute, thereby creating an incentive
1385 /// to restrict `htlc_maximum_msat` and improve privacy.
1387 /// Default value: 250 msat
1389 pub extern "C" fn ProbabilisticScoringFeeParameters_get_anti_probing_penalty_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1390 let mut inner_val = &mut this_ptr.get_native_mut_ref().anti_probing_penalty_msat;
1393 /// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
1394 /// channel's capacity, (ie. htlc_maximum_msat >= 0.5 * channel_capacity) which makes us
1395 /// prefer nodes with a smaller `htlc_maximum_msat`. We treat such nodes preferentially
1396 /// as this makes balance discovery attacks harder to execute, thereby creating an incentive
1397 /// to restrict `htlc_maximum_msat` and improve privacy.
1399 /// Default value: 250 msat
1401 pub extern "C" fn ProbabilisticScoringFeeParameters_set_anti_probing_penalty_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1402 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.anti_probing_penalty_msat = val;
1404 /// This penalty is applied when the total amount flowing over a channel exceeds our current
1405 /// estimate of the channel's available liquidity. The total amount is the amount of the
1406 /// current HTLC plus any HTLCs which we've sent over the same channel.
1408 /// Note that in this case all other penalties, including the
1409 /// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
1410 /// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
1411 /// applicable, are still included in the overall penalty.
1413 /// If you wish to avoid creating paths with such channels entirely, setting this to a value of
1414 /// `u64::max_value()` will guarantee that.
1416 /// Default value: 1_0000_0000_000 msat (1 Bitcoin)
1418 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1419 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1420 /// [`base_penalty_msat`]: Self::base_penalty_msat
1421 /// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
1423 pub extern "C" fn ProbabilisticScoringFeeParameters_get_considered_impossible_penalty_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1424 let mut inner_val = &mut this_ptr.get_native_mut_ref().considered_impossible_penalty_msat;
1427 /// This penalty is applied when the total amount flowing over a channel exceeds our current
1428 /// estimate of the channel's available liquidity. The total amount is the amount of the
1429 /// current HTLC plus any HTLCs which we've sent over the same channel.
1431 /// Note that in this case all other penalties, including the
1432 /// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
1433 /// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
1434 /// applicable, are still included in the overall penalty.
1436 /// If you wish to avoid creating paths with such channels entirely, setting this to a value of
1437 /// `u64::max_value()` will guarantee that.
1439 /// Default value: 1_0000_0000_000 msat (1 Bitcoin)
1441 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1442 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1443 /// [`base_penalty_msat`]: Self::base_penalty_msat
1444 /// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
1446 pub extern "C" fn ProbabilisticScoringFeeParameters_set_considered_impossible_penalty_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1447 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.considered_impossible_penalty_msat = val;
1449 /// In order to calculate most of the scores above, we must first convert a lower and upper
1450 /// bound on the available liquidity in a channel into the probability that we think a payment
1451 /// will succeed. That probability is derived from a Probability Density Function for where we
1452 /// think the liquidity in a channel likely lies, given such bounds.
1454 /// If this flag is set, that PDF is simply a constant - we assume that the actual available
1455 /// liquidity in a channel is just as likely to be at any point between our lower and upper
1458 /// If this flag is *not* set, that PDF is `(x - 0.5*capacity) ^ 2`. That is, we use an
1459 /// exponential curve which expects the liquidity of a channel to lie \"at the edges\". This
1460 /// matches experimental results - most routing nodes do not aggressively rebalance their
1461 /// channels and flows in the network are often unbalanced, leaving liquidity usually
1464 /// Thus, for the \"best\" routes, leave this flag `false`. However, the flag does imply a number
1465 /// of floating-point multiplications in the hottest routing code, which may lead to routing
1466 /// performance degradation on some machines.
1468 /// Default value: false
1470 pub extern "C" fn ProbabilisticScoringFeeParameters_get_linear_success_probability(this_ptr: &ProbabilisticScoringFeeParameters) -> bool {
1471 let mut inner_val = &mut this_ptr.get_native_mut_ref().linear_success_probability;
1474 /// In order to calculate most of the scores above, we must first convert a lower and upper
1475 /// bound on the available liquidity in a channel into the probability that we think a payment
1476 /// will succeed. That probability is derived from a Probability Density Function for where we
1477 /// think the liquidity in a channel likely lies, given such bounds.
1479 /// If this flag is set, that PDF is simply a constant - we assume that the actual available
1480 /// liquidity in a channel is just as likely to be at any point between our lower and upper
1483 /// If this flag is *not* set, that PDF is `(x - 0.5*capacity) ^ 2`. That is, we use an
1484 /// exponential curve which expects the liquidity of a channel to lie \"at the edges\". This
1485 /// matches experimental results - most routing nodes do not aggressively rebalance their
1486 /// channels and flows in the network are often unbalanced, leaving liquidity usually
1489 /// Thus, for the \"best\" routes, leave this flag `false`. However, the flag does imply a number
1490 /// of floating-point multiplications in the hottest routing code, which may lead to routing
1491 /// performance degradation on some machines.
1493 /// Default value: false
1495 pub extern "C" fn ProbabilisticScoringFeeParameters_set_linear_success_probability(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: bool) {
1496 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.linear_success_probability = val;
1498 impl Clone for ProbabilisticScoringFeeParameters {
1499 fn clone(&self) -> Self {
1501 inner: if <*mut nativeProbabilisticScoringFeeParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
1502 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
1508 /// Used only if an object of this type is returned as a trait impl by a method
1509 pub(crate) extern "C" fn ProbabilisticScoringFeeParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
1510 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeProbabilisticScoringFeeParameters)).clone() })) as *mut c_void
1513 /// Creates a copy of the ProbabilisticScoringFeeParameters
1514 pub extern "C" fn ProbabilisticScoringFeeParameters_clone(orig: &ProbabilisticScoringFeeParameters) -> ProbabilisticScoringFeeParameters {
1517 /// Creates a "default" ProbabilisticScoringFeeParameters. See struct and individual field documentaiton for details on which values are used.
1520 pub extern "C" fn ProbabilisticScoringFeeParameters_default() -> ProbabilisticScoringFeeParameters {
1521 ProbabilisticScoringFeeParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
1523 /// Marks the node with the given `node_id` as banned,
1524 /// i.e it will be avoided during path finding.
1526 pub extern "C" fn ProbabilisticScoringFeeParameters_add_banned(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters, node_id: &crate::lightning::routing::gossip::NodeId) {
1527 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.add_banned(node_id.get_native_ref())
1530 /// Marks all nodes in the given list as banned, i.e.,
1531 /// they will be avoided during path finding.
1533 pub extern "C" fn ProbabilisticScoringFeeParameters_add_banned_from_list(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters, mut node_ids: crate::c_types::derived::CVec_NodeIdZ) {
1534 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()) } }); };
1535 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.add_banned_from_list(local_node_ids)
1538 /// Removes the node with the given `node_id` from the list of nodes to avoid.
1540 pub extern "C" fn ProbabilisticScoringFeeParameters_remove_banned(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters, node_id: &crate::lightning::routing::gossip::NodeId) {
1541 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.remove_banned(node_id.get_native_ref())
1544 /// Sets a manual penalty for the given node.
1546 pub extern "C" fn ProbabilisticScoringFeeParameters_set_manual_penalty(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters, node_id: &crate::lightning::routing::gossip::NodeId, mut penalty: u64) {
1547 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.set_manual_penalty(node_id.get_native_ref(), penalty)
1550 /// Removes the node with the given `node_id` from the list of manual penalties.
1552 pub extern "C" fn ProbabilisticScoringFeeParameters_remove_manual_penalty(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters, node_id: &crate::lightning::routing::gossip::NodeId) {
1553 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.remove_manual_penalty(node_id.get_native_ref())
1556 /// Clears the list of manual penalties that are applied during path finding.
1558 pub extern "C" fn ProbabilisticScoringFeeParameters_clear_manual_penalties(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) {
1559 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.clear_manual_penalties()
1563 use lightning::routing::scoring::ProbabilisticScoringDecayParameters as nativeProbabilisticScoringDecayParametersImport;
1564 pub(crate) type nativeProbabilisticScoringDecayParameters = nativeProbabilisticScoringDecayParametersImport;
1566 /// Parameters for configuring [`ProbabilisticScorer`].
1568 /// Used to configure decay parameters that are static throughout the lifetime of the scorer.
1569 /// these decay parameters affect the score of the channel penalty and are not changed on a
1570 /// per-route penalty cost call.
1573 pub struct ProbabilisticScoringDecayParameters {
1574 /// A pointer to the opaque Rust object.
1576 /// Nearly everywhere, inner must be non-null, however in places where
1577 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
1578 pub inner: *mut nativeProbabilisticScoringDecayParameters,
1579 /// Indicates that this is the only struct which contains the same pointer.
1581 /// Rust functions which take ownership of an object provided via an argument require
1582 /// this to be true and invalidate the object pointed to by inner.
1586 impl Drop for ProbabilisticScoringDecayParameters {
1587 fn drop(&mut self) {
1588 if self.is_owned && !<*mut nativeProbabilisticScoringDecayParameters>::is_null(self.inner) {
1589 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
1593 /// Frees any resources used by the ProbabilisticScoringDecayParameters, if is_owned is set and inner is non-NULL.
1595 pub extern "C" fn ProbabilisticScoringDecayParameters_free(this_obj: ProbabilisticScoringDecayParameters) { }
1597 /// Used only if an object of this type is returned as a trait impl by a method
1598 pub(crate) extern "C" fn ProbabilisticScoringDecayParameters_free_void(this_ptr: *mut c_void) {
1599 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeProbabilisticScoringDecayParameters) };
1602 impl ProbabilisticScoringDecayParameters {
1603 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringDecayParameters {
1604 unsafe { &*ObjOps::untweak_ptr(self.inner) }
1606 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringDecayParameters {
1607 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
1609 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
1610 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringDecayParameters {
1611 assert!(self.is_owned);
1612 let ret = ObjOps::untweak_ptr(self.inner);
1613 self.inner = core::ptr::null_mut();
1617 /// If we aren't learning any new datapoints for a channel, the historical liquidity bounds
1618 /// tracking can simply live on with increasingly stale data. Instead, when a channel has not
1619 /// seen a liquidity estimate update for this amount of time, the historical datapoints are
1620 /// decayed by half.
1621 /// For an example of historical_no_updates_half_life being used see [`historical_estimated_channel_liquidity_probabilities`]
1623 /// Note that after 16 or more half lives all historical data will be completely gone.
1625 /// Default value: 14 days
1627 /// [`historical_estimated_channel_liquidity_probabilities`]: ProbabilisticScorerUsingTime::historical_estimated_channel_liquidity_probabilities
1629 pub extern "C" fn ProbabilisticScoringDecayParameters_get_historical_no_updates_half_life(this_ptr: &ProbabilisticScoringDecayParameters) -> u64 {
1630 let mut inner_val = &mut this_ptr.get_native_mut_ref().historical_no_updates_half_life;
1633 /// If we aren't learning any new datapoints for a channel, the historical liquidity bounds
1634 /// tracking can simply live on with increasingly stale data. Instead, when a channel has not
1635 /// seen a liquidity estimate update for this amount of time, the historical datapoints are
1636 /// decayed by half.
1637 /// For an example of historical_no_updates_half_life being used see [`historical_estimated_channel_liquidity_probabilities`]
1639 /// Note that after 16 or more half lives all historical data will be completely gone.
1641 /// Default value: 14 days
1643 /// [`historical_estimated_channel_liquidity_probabilities`]: ProbabilisticScorerUsingTime::historical_estimated_channel_liquidity_probabilities
1645 pub extern "C" fn ProbabilisticScoringDecayParameters_set_historical_no_updates_half_life(this_ptr: &mut ProbabilisticScoringDecayParameters, mut val: u64) {
1646 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.historical_no_updates_half_life = core::time::Duration::from_secs(val);
1648 /// Whenever this amount of time elapses since the last update to a channel's liquidity bounds,
1649 /// the distance from the bounds to \"zero\" is cut in half. In other words, the lower-bound on
1650 /// the available liquidity is halved and the upper-bound moves half-way to the channel's total
1653 /// Because halving the liquidity bounds grows the uncertainty on the channel's liquidity,
1654 /// the penalty for an amount within the new bounds may change. See the [`ProbabilisticScorer`]
1655 /// struct documentation for more info on the way the liquidity bounds are used.
1657 /// For example, if the channel's capacity is 1 million sats, and the current upper and lower
1658 /// liquidity bounds are 200,000 sats and 600,000 sats, after this amount of time the upper
1659 /// and lower liquidity bounds will be decayed to 100,000 and 800,000 sats.
1661 /// Default value: 6 hours
1665 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
1666 /// liquidity knowledge will never decay except when the bounds cross.
1668 pub extern "C" fn ProbabilisticScoringDecayParameters_get_liquidity_offset_half_life(this_ptr: &ProbabilisticScoringDecayParameters) -> u64 {
1669 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_offset_half_life;
1672 /// Whenever this amount of time elapses since the last update to a channel's liquidity bounds,
1673 /// the distance from the bounds to \"zero\" is cut in half. In other words, the lower-bound on
1674 /// the available liquidity is halved and the upper-bound moves half-way to the channel's total
1677 /// Because halving the liquidity bounds grows the uncertainty on the channel's liquidity,
1678 /// the penalty for an amount within the new bounds may change. See the [`ProbabilisticScorer`]
1679 /// struct documentation for more info on the way the liquidity bounds are used.
1681 /// For example, if the channel's capacity is 1 million sats, and the current upper and lower
1682 /// liquidity bounds are 200,000 sats and 600,000 sats, after this amount of time the upper
1683 /// and lower liquidity bounds will be decayed to 100,000 and 800,000 sats.
1685 /// Default value: 6 hours
1689 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
1690 /// liquidity knowledge will never decay except when the bounds cross.
1692 pub extern "C" fn ProbabilisticScoringDecayParameters_set_liquidity_offset_half_life(this_ptr: &mut ProbabilisticScoringDecayParameters, mut val: u64) {
1693 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_offset_half_life = core::time::Duration::from_secs(val);
1695 /// Constructs a new ProbabilisticScoringDecayParameters given each field
1698 pub extern "C" fn ProbabilisticScoringDecayParameters_new(mut historical_no_updates_half_life_arg: u64, mut liquidity_offset_half_life_arg: u64) -> ProbabilisticScoringDecayParameters {
1699 ProbabilisticScoringDecayParameters { inner: ObjOps::heap_alloc(nativeProbabilisticScoringDecayParameters {
1700 historical_no_updates_half_life: core::time::Duration::from_secs(historical_no_updates_half_life_arg),
1701 liquidity_offset_half_life: core::time::Duration::from_secs(liquidity_offset_half_life_arg),
1702 }), is_owned: true }
1704 impl Clone for ProbabilisticScoringDecayParameters {
1705 fn clone(&self) -> Self {
1707 inner: if <*mut nativeProbabilisticScoringDecayParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
1708 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
1714 /// Used only if an object of this type is returned as a trait impl by a method
1715 pub(crate) extern "C" fn ProbabilisticScoringDecayParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
1716 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeProbabilisticScoringDecayParameters)).clone() })) as *mut c_void
1719 /// Creates a copy of the ProbabilisticScoringDecayParameters
1720 pub extern "C" fn ProbabilisticScoringDecayParameters_clone(orig: &ProbabilisticScoringDecayParameters) -> ProbabilisticScoringDecayParameters {
1723 /// Creates a "default" ProbabilisticScoringDecayParameters. See struct and individual field documentaiton for details on which values are used.
1726 pub extern "C" fn ProbabilisticScoringDecayParameters_default() -> ProbabilisticScoringDecayParameters {
1727 ProbabilisticScoringDecayParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
1729 /// Creates a new scorer using the given scoring parameters for sending payments from a node
1730 /// through a network graph.
1733 pub extern "C" fn ProbabilisticScorer_new(mut decay_params: crate::lightning::routing::scoring::ProbabilisticScoringDecayParameters, network_graph: &crate::lightning::routing::gossip::NetworkGraph, mut logger: crate::lightning::util::logger::Logger) -> crate::lightning::routing::scoring::ProbabilisticScorer {
1734 let mut ret = lightning::routing::scoring::ProbabilisticScorer::new(*unsafe { Box::from_raw(decay_params.take_inner()) }, network_graph.get_native_ref(), logger);
1735 crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
1738 /// Dump the contents of this scorer into the configured logger.
1740 /// Note that this writes roughly one line per channel for which we have a liquidity estimate,
1741 /// which may be a substantial amount of log output.
1743 pub extern "C" fn ProbabilisticScorer_debug_log_liquidity_stats(this_arg: &crate::lightning::routing::scoring::ProbabilisticScorer) {
1744 unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.debug_log_liquidity_stats()
1747 /// Query the estimated minimum and maximum liquidity available for sending a payment over the
1748 /// channel with `scid` towards the given `target` node.
1751 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 {
1752 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.estimated_channel_liquidity_range(scid, target.get_native_ref());
1753 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 }) };
1757 /// Query the historical estimated minimum and maximum liquidity available for sending a
1758 /// payment over the channel with `scid` towards the given `target` node.
1760 /// Returns two sets of 32 buckets. The first set describes the lower-bound liquidity history,
1761 /// the second set describes the upper-bound liquidity history. Each bucket describes the
1762 /// relative frequency at which we've seen a liquidity bound in the bucket's range relative to
1763 /// the channel's total capacity, on an arbitrary scale. Because the values are slowly decayed,
1764 /// more recent data points are weighted more heavily than older datapoints.
1766 /// Note that the range of each bucket varies by its location to provide more granular results
1767 /// at the edges of a channel's capacity, where it is more likely to sit.
1769 /// When scoring, the estimated probability that an upper-/lower-bound lies in a given bucket
1770 /// is calculated by dividing that bucket's value with the total value of all buckets.
1772 /// For example, using a lower bucket count for illustrative purposes, a value of
1773 /// `[0, 0, 0, ..., 0, 32]` indicates that we believe the probability of a bound being very
1774 /// close to the channel's capacity to be 100%, and have never (recently) seen it in any other
1775 /// bucket. A value of `[31, 0, 0, ..., 0, 0, 32]` indicates we've seen the bound being both
1776 /// in the top and bottom bucket, and roughly with similar (recent) frequency.
1778 /// Because the datapoints are decayed slowly over time, values will eventually return to
1779 /// `Some(([1; 32], [1; 32]))` and then to `None` once no datapoints remain.
1781 /// In order to fetch a single success probability from the buckets provided here, as used in
1782 /// the scoring model, see [`Self::historical_estimated_payment_success_probability`].
1785 pub extern "C" fn ProbabilisticScorer_historical_estimated_channel_liquidity_probabilities(this_arg: &crate::lightning::routing::scoring::ProbabilisticScorer, mut scid: u64, target: &crate::lightning::routing::gossip::NodeId) -> crate::c_types::derived::COption_C2Tuple_ThirtyTwoU16sThirtyTwoU16sZZ {
1786 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.historical_estimated_channel_liquidity_probabilities(scid, target.get_native_ref());
1787 let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_C2Tuple_ThirtyTwoU16sThirtyTwoU16sZZ::None } else { crate::c_types::derived::COption_C2Tuple_ThirtyTwoU16sThirtyTwoU16sZZ::Some( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (ret.unwrap()); let mut local_ret_0 = (crate::c_types::ThirtyTwoU16s { data: orig_ret_0_0 }, crate::c_types::ThirtyTwoU16s { data: orig_ret_0_1 }).into(); local_ret_0 }) };
1791 /// Query the probability of payment success sending the given `amount_msat` over the channel
1792 /// with `scid` towards the given `target` node, based on the historical estimated liquidity
1795 /// These are the same bounds as returned by
1796 /// [`Self::historical_estimated_channel_liquidity_probabilities`] (but not those returned by
1797 /// [`Self::estimated_channel_liquidity_range`]).
1800 pub extern "C" fn ProbabilisticScorer_historical_estimated_payment_success_probability(this_arg: &crate::lightning::routing::scoring::ProbabilisticScorer, mut scid: u64, target: &crate::lightning::routing::gossip::NodeId, mut amount_msat: u64, params: &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> crate::c_types::derived::COption_f64Z {
1801 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.historical_estimated_payment_success_probability(scid, target.get_native_ref(), amount_msat, params.get_native_ref());
1802 let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_f64Z::None } else { crate::c_types::derived::COption_f64Z::Some( { ret.unwrap() }) };
1806 impl From<nativeProbabilisticScorer> for crate::lightning::routing::scoring::ScoreLookUp {
1807 fn from(obj: nativeProbabilisticScorer) -> Self {
1808 let rust_obj = crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
1809 let mut ret = ProbabilisticScorer_as_ScoreLookUp(&rust_obj);
1810 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
1811 core::mem::forget(rust_obj);
1812 ret.free = Some(ProbabilisticScorer_free_void);
1816 /// Constructs a new ScoreLookUp which calls the relevant methods on this_arg.
1817 /// This copies the `inner` pointer in this_arg and thus the returned ScoreLookUp must be freed before this_arg is
1819 pub extern "C" fn ProbabilisticScorer_as_ScoreLookUp(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::ScoreLookUp {
1820 crate::lightning::routing::scoring::ScoreLookUp {
1821 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1823 channel_penalty_msat: ProbabilisticScorer_ScoreLookUp_channel_penalty_msat,
1828 extern "C" fn ProbabilisticScorer_ScoreLookUp_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, mut usage: crate::lightning::routing::scoring::ChannelUsage, score_params: &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
1829 let mut ret = <nativeProbabilisticScorer as lightning::routing::scoring::ScoreLookUp<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, short_channel_id, source.get_native_ref(), target.get_native_ref(), *unsafe { Box::from_raw(usage.take_inner()) }, score_params.get_native_ref());
1833 impl From<nativeProbabilisticScorer> for crate::lightning::routing::scoring::ScoreUpdate {
1834 fn from(obj: nativeProbabilisticScorer) -> Self {
1835 let rust_obj = crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
1836 let mut ret = ProbabilisticScorer_as_ScoreUpdate(&rust_obj);
1837 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
1838 core::mem::forget(rust_obj);
1839 ret.free = Some(ProbabilisticScorer_free_void);
1843 /// Constructs a new ScoreUpdate which calls the relevant methods on this_arg.
1844 /// This copies the `inner` pointer in this_arg and thus the returned ScoreUpdate must be freed before this_arg is
1846 pub extern "C" fn ProbabilisticScorer_as_ScoreUpdate(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::ScoreUpdate {
1847 crate::lightning::routing::scoring::ScoreUpdate {
1848 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1850 payment_path_failed: ProbabilisticScorer_ScoreUpdate_payment_path_failed,
1851 payment_path_successful: ProbabilisticScorer_ScoreUpdate_payment_path_successful,
1852 probe_failed: ProbabilisticScorer_ScoreUpdate_probe_failed,
1853 probe_successful: ProbabilisticScorer_ScoreUpdate_probe_successful,
1857 extern "C" fn ProbabilisticScorer_ScoreUpdate_payment_path_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
1858 <nativeProbabilisticScorer as lightning::routing::scoring::ScoreUpdate<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref(), short_channel_id)
1860 extern "C" fn ProbabilisticScorer_ScoreUpdate_payment_path_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
1861 <nativeProbabilisticScorer as lightning::routing::scoring::ScoreUpdate<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref())
1863 extern "C" fn ProbabilisticScorer_ScoreUpdate_probe_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
1864 <nativeProbabilisticScorer as lightning::routing::scoring::ScoreUpdate<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref(), short_channel_id)
1866 extern "C" fn ProbabilisticScorer_ScoreUpdate_probe_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
1867 <nativeProbabilisticScorer as lightning::routing::scoring::ScoreUpdate<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref())
1870 impl From<nativeProbabilisticScorer> for crate::lightning::routing::scoring::Score {
1871 fn from(obj: nativeProbabilisticScorer) -> Self {
1872 let rust_obj = crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
1873 let mut ret = ProbabilisticScorer_as_Score(&rust_obj);
1874 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
1875 core::mem::forget(rust_obj);
1876 ret.free = Some(ProbabilisticScorer_free_void);
1880 /// Constructs a new Score which calls the relevant methods on this_arg.
1881 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
1883 pub extern "C" fn ProbabilisticScorer_as_Score(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::Score {
1884 crate::lightning::routing::scoring::Score {
1885 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1887 ScoreLookUp: crate::lightning::routing::scoring::ScoreLookUp {
1888 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1890 channel_penalty_msat: ProbabilisticScorer_ScoreLookUp_channel_penalty_msat,
1892 ScoreUpdate: crate::lightning::routing::scoring::ScoreUpdate {
1893 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1895 payment_path_failed: ProbabilisticScorer_ScoreUpdate_payment_path_failed,
1896 payment_path_successful: ProbabilisticScorer_ScoreUpdate_payment_path_successful,
1897 probe_failed: ProbabilisticScorer_ScoreUpdate_probe_failed,
1898 probe_successful: ProbabilisticScorer_ScoreUpdate_probe_successful,
1900 write: ProbabilisticScorer_write_void,
1907 use alloc::str::FromStr;
1908 use alloc::string::String;
1909 use core::ffi::c_void;
1910 use core::convert::Infallible;
1911 use bitcoin::hashes::Hash;
1912 use crate::c_types::*;
1913 #[cfg(feature="no-std")]
1914 use alloc::{vec::Vec, boxed::Box};
1917 mod bucketed_history {
1919 use alloc::str::FromStr;
1920 use alloc::string::String;
1921 use core::ffi::c_void;
1922 use core::convert::Infallible;
1923 use bitcoin::hashes::Hash;
1924 use crate::c_types::*;
1925 #[cfg(feature="no-std")]
1926 use alloc::{vec::Vec, boxed::Box};
1930 /// Serialize the ProbabilisticScorer object into a byte array which can be read by ProbabilisticScorer_read
1931 pub extern "C" fn ProbabilisticScorer_write(obj: &crate::lightning::routing::scoring::ProbabilisticScorer) -> crate::c_types::derived::CVec_u8Z {
1932 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
1935 pub(crate) extern "C" fn ProbabilisticScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
1936 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeProbabilisticScorer) })
1939 /// Read a ProbabilisticScorer from a byte array, created by ProbabilisticScorer_write
1940 pub extern "C" fn ProbabilisticScorer_read(ser: crate::c_types::u8slice, arg_a: crate::lightning::routing::scoring::ProbabilisticScoringDecayParameters, arg_b: &crate::lightning::routing::gossip::NetworkGraph, arg_c: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_ProbabilisticScorerDecodeErrorZ {
1941 let arg_a_conv = *unsafe { Box::from_raw(arg_a.take_inner()) };
1942 let arg_b_conv = arg_b.get_native_ref();
1943 let arg_c_conv = arg_c;
1944 let arg_conv = (arg_a_conv, arg_b_conv, arg_c_conv);
1945 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);
1946 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() };