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, candidate: &crate::lightning::routing::router::CandidateRouteHop, 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 candidate: &lightning::routing::router::CandidateRouteHop, 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, &crate::lightning::routing::router::CandidateRouteHop::from_native(candidate), 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, duration_since_epoch: 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, duration_since_epoch: u64),
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, duration_since_epoch: 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, duration_since_epoch: u64),
146 /// Scorers may wish to reduce their certainty of channel liquidity information over time.
147 /// Thus, this method is provided to allow scorers to observe the passage of time - the holder
148 /// of this object should call this method regularly (generally via the
149 /// `lightning-background-processor` crate).
150 pub time_passed: extern "C" fn (this_arg: *mut c_void, duration_since_epoch: u64),
151 /// Frees any resources associated with this object given its this_arg pointer.
152 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
153 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
155 unsafe impl Send for ScoreUpdate {}
156 unsafe impl Sync for ScoreUpdate {}
158 pub(crate) fn ScoreUpdate_clone_fields(orig: &ScoreUpdate) -> ScoreUpdate {
160 this_arg: orig.this_arg,
161 payment_path_failed: Clone::clone(&orig.payment_path_failed),
162 payment_path_successful: Clone::clone(&orig.payment_path_successful),
163 probe_failed: Clone::clone(&orig.probe_failed),
164 probe_successful: Clone::clone(&orig.probe_successful),
165 time_passed: Clone::clone(&orig.time_passed),
166 free: Clone::clone(&orig.free),
170 use lightning::routing::scoring::ScoreUpdate as rustScoreUpdate;
171 impl rustScoreUpdate for ScoreUpdate {
172 fn payment_path_failed(&mut self, mut path: &lightning::routing::router::Path, mut short_channel_id: u64, mut duration_since_epoch: core::time::Duration) {
173 (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, duration_since_epoch.as_secs())
175 fn payment_path_successful(&mut self, mut path: &lightning::routing::router::Path, mut duration_since_epoch: core::time::Duration) {
176 (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 }, duration_since_epoch.as_secs())
178 fn probe_failed(&mut self, mut path: &lightning::routing::router::Path, mut short_channel_id: u64, mut duration_since_epoch: core::time::Duration) {
179 (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, duration_since_epoch.as_secs())
181 fn probe_successful(&mut self, mut path: &lightning::routing::router::Path, mut duration_since_epoch: core::time::Duration) {
182 (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 }, duration_since_epoch.as_secs())
184 fn time_passed(&mut self, mut duration_since_epoch: core::time::Duration) {
185 (self.time_passed)(self.this_arg, duration_since_epoch.as_secs())
189 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
190 // directly as a Deref trait in higher-level structs:
191 impl core::ops::Deref for ScoreUpdate {
193 fn deref(&self) -> &Self {
197 impl core::ops::DerefMut for ScoreUpdate {
198 fn deref_mut(&mut self) -> &mut Self {
202 /// Calls the free function if one is set
204 pub extern "C" fn ScoreUpdate_free(this_ptr: ScoreUpdate) { }
205 impl Drop for ScoreUpdate {
207 if let Some(f) = self.free {
212 /// A trait which can both lookup and update routing channel penalty scores.
214 /// This is used in places where both bounds are required and implemented for all types which
215 /// implement [`ScoreLookUp`] and [`ScoreUpdate`].
217 /// Bindings users may need to manually implement this for their custom scoring implementations.
220 /// An opaque pointer which is passed to your function implementations as an argument.
221 /// This has no meaning in the LDK, and can be NULL or any other value.
222 pub this_arg: *mut c_void,
223 /// Implementation of ScoreLookUp for this object.
224 pub ScoreLookUp: crate::lightning::routing::scoring::ScoreLookUp,
225 /// Implementation of ScoreUpdate for this object.
226 pub ScoreUpdate: crate::lightning::routing::scoring::ScoreUpdate,
227 /// Serialize the object into a byte array
228 pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
229 /// Frees any resources associated with this object given its this_arg pointer.
230 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
231 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
233 unsafe impl Send for Score {}
234 unsafe impl Sync for Score {}
236 pub(crate) fn Score_clone_fields(orig: &Score) -> Score {
238 this_arg: orig.this_arg,
239 ScoreLookUp: crate::lightning::routing::scoring::ScoreLookUp_clone_fields(&orig.ScoreLookUp),
240 ScoreUpdate: crate::lightning::routing::scoring::ScoreUpdate_clone_fields(&orig.ScoreUpdate),
241 write: Clone::clone(&orig.write),
242 free: Clone::clone(&orig.free),
245 impl lightning::routing::scoring::ScoreLookUp for Score {
246 fn channel_penalty_msat(&self, mut candidate: &lightning::routing::router::CandidateRouteHop, mut usage: lightning::routing::scoring::ChannelUsage, mut score_params: &lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
247 let mut ret = (self.ScoreLookUp.channel_penalty_msat)(self.ScoreLookUp.this_arg, &crate::lightning::routing::router::CandidateRouteHop::from_native(candidate), 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 });
251 impl lightning::routing::scoring::ScoreUpdate for Score {
252 fn payment_path_failed(&mut self, mut path: &lightning::routing::router::Path, mut short_channel_id: u64, mut duration_since_epoch: core::time::Duration) {
253 (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, duration_since_epoch.as_secs())
255 fn payment_path_successful(&mut self, mut path: &lightning::routing::router::Path, mut duration_since_epoch: core::time::Duration) {
256 (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 }, duration_since_epoch.as_secs())
258 fn probe_failed(&mut self, mut path: &lightning::routing::router::Path, mut short_channel_id: u64, mut duration_since_epoch: core::time::Duration) {
259 (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, duration_since_epoch.as_secs())
261 fn probe_successful(&mut self, mut path: &lightning::routing::router::Path, mut duration_since_epoch: core::time::Duration) {
262 (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 }, duration_since_epoch.as_secs())
264 fn time_passed(&mut self, mut duration_since_epoch: core::time::Duration) {
265 (self.ScoreUpdate.time_passed)(self.ScoreUpdate.this_arg, duration_since_epoch.as_secs())
268 impl lightning::util::ser::Writeable for Score {
269 fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
270 let vec = (self.write)(self.this_arg);
271 w.write_all(vec.as_slice())
275 use lightning::routing::scoring::Score as rustScore;
276 impl rustScore for Score {
279 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
280 // directly as a Deref trait in higher-level structs:
281 impl core::ops::Deref for Score {
283 fn deref(&self) -> &Self {
287 impl core::ops::DerefMut for Score {
288 fn deref_mut(&mut self) -> &mut Self {
292 /// Calls the free function if one is set
294 pub extern "C" fn Score_free(this_ptr: Score) { }
295 impl Drop for Score {
297 if let Some(f) = self.free {
302 /// A scorer that is accessed under a lock.
304 /// Needed so that calls to [`ScoreLookUp::channel_penalty_msat`] in [`find_route`] can be made while
305 /// having shared ownership of a scorer but without requiring internal locking in [`ScoreUpdate`]
306 /// implementations. Internal locking would be detrimental to route finding performance and could
307 /// result in [`ScoreLookUp::channel_penalty_msat`] returning a different value for the same channel.
309 /// [`find_route`]: crate::routing::router::find_route
311 pub struct LockableScore {
312 /// An opaque pointer which is passed to your function implementations as an argument.
313 /// This has no meaning in the LDK, and can be NULL or any other value.
314 pub this_arg: *mut c_void,
315 /// Returns read locked scorer.
316 pub read_lock: extern "C" fn (this_arg: *const c_void) -> crate::lightning::routing::scoring::ScoreLookUp,
317 /// Returns write locked scorer.
318 pub write_lock: extern "C" fn (this_arg: *const c_void) -> crate::lightning::routing::scoring::ScoreUpdate,
319 /// Frees any resources associated with this object given its this_arg pointer.
320 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
321 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
323 unsafe impl Send for LockableScore {}
324 unsafe impl Sync for LockableScore {}
326 pub(crate) fn LockableScore_clone_fields(orig: &LockableScore) -> LockableScore {
328 this_arg: orig.this_arg,
329 read_lock: Clone::clone(&orig.read_lock),
330 write_lock: Clone::clone(&orig.write_lock),
331 free: Clone::clone(&orig.free),
335 use lightning::routing::scoring::LockableScore as rustLockableScore;
336 impl<'a> rustLockableScore<'a, > for LockableScore {
337 type ScoreUpdate = crate::lightning::routing::scoring::ScoreUpdate;
338 type ScoreLookUp = crate::lightning::routing::scoring::ScoreLookUp;
339 type WriteLocked = crate::lightning::routing::scoring::ScoreUpdate;
340 type ReadLocked = crate::lightning::routing::scoring::ScoreLookUp;
341 fn read_lock(&'a self) -> crate::lightning::routing::scoring::ScoreLookUp {
342 let mut ret = (self.read_lock)(self.this_arg);
345 fn write_lock(&'a self) -> crate::lightning::routing::scoring::ScoreUpdate {
346 let mut ret = (self.write_lock)(self.this_arg);
351 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
352 // directly as a Deref trait in higher-level structs:
353 impl core::ops::Deref for LockableScore {
355 fn deref(&self) -> &Self {
359 impl core::ops::DerefMut for LockableScore {
360 fn deref_mut(&mut self) -> &mut Self {
364 /// Calls the free function if one is set
366 pub extern "C" fn LockableScore_free(this_ptr: LockableScore) { }
367 impl Drop for LockableScore {
369 if let Some(f) = self.free {
374 /// Refers to a scorer that is accessible under lock and also writeable to disk
376 /// We need this trait to be able to pass in a scorer to `lightning-background-processor` that will enable us to
377 /// use the Persister to persist it.
379 pub struct WriteableScore {
380 /// An opaque pointer which is passed to your function implementations as an argument.
381 /// This has no meaning in the LDK, and can be NULL or any other value.
382 pub this_arg: *mut c_void,
383 /// Implementation of LockableScore for this object.
384 pub LockableScore: crate::lightning::routing::scoring::LockableScore,
385 /// Serialize the object into a byte array
386 pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
387 /// Frees any resources associated with this object given its this_arg pointer.
388 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
389 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
391 unsafe impl Send for WriteableScore {}
392 unsafe impl Sync for WriteableScore {}
394 pub(crate) fn WriteableScore_clone_fields(orig: &WriteableScore) -> WriteableScore {
396 this_arg: orig.this_arg,
397 LockableScore: crate::lightning::routing::scoring::LockableScore_clone_fields(&orig.LockableScore),
398 write: Clone::clone(&orig.write),
399 free: Clone::clone(&orig.free),
402 impl<'a> lightning::routing::scoring::LockableScore<'a, > for WriteableScore {
403 type ScoreUpdate = crate::lightning::routing::scoring::ScoreUpdate;
404 type ScoreLookUp = crate::lightning::routing::scoring::ScoreLookUp;
405 type WriteLocked = crate::lightning::routing::scoring::ScoreUpdate;
406 type ReadLocked = crate::lightning::routing::scoring::ScoreLookUp;
407 fn read_lock(&'a self) -> crate::lightning::routing::scoring::ScoreLookUp {
408 let mut ret = (self.LockableScore.read_lock)(self.LockableScore.this_arg);
411 fn write_lock(&'a self) -> crate::lightning::routing::scoring::ScoreUpdate {
412 let mut ret = (self.LockableScore.write_lock)(self.LockableScore.this_arg);
416 impl lightning::util::ser::Writeable for WriteableScore {
417 fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
418 let vec = (self.write)(self.this_arg);
419 w.write_all(vec.as_slice())
423 use lightning::routing::scoring::WriteableScore as rustWriteableScore;
424 impl<'a> rustWriteableScore<'a, > for WriteableScore {
427 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
428 // directly as a Deref trait in higher-level structs:
429 impl core::ops::Deref for WriteableScore {
431 fn deref(&self) -> &Self {
435 impl core::ops::DerefMut for WriteableScore {
436 fn deref_mut(&mut self) -> &mut Self {
440 /// Calls the free function if one is set
442 pub extern "C" fn WriteableScore_free(this_ptr: WriteableScore) { }
443 impl Drop for WriteableScore {
445 if let Some(f) = self.free {
451 use lightning::routing::scoring::MultiThreadedLockableScore as nativeMultiThreadedLockableScoreImport;
452 pub(crate) type nativeMultiThreadedLockableScore = nativeMultiThreadedLockableScoreImport<crate::lightning::routing::scoring::Score, >;
454 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
457 pub struct MultiThreadedLockableScore {
458 /// A pointer to the opaque Rust object.
460 /// Nearly everywhere, inner must be non-null, however in places where
461 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
462 pub inner: *mut nativeMultiThreadedLockableScore,
463 /// Indicates that this is the only struct which contains the same pointer.
465 /// Rust functions which take ownership of an object provided via an argument require
466 /// this to be true and invalidate the object pointed to by inner.
470 impl Drop for MultiThreadedLockableScore {
472 if self.is_owned && !<*mut nativeMultiThreadedLockableScore>::is_null(self.inner) {
473 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
477 /// Frees any resources used by the MultiThreadedLockableScore, if is_owned is set and inner is non-NULL.
479 pub extern "C" fn MultiThreadedLockableScore_free(this_obj: MultiThreadedLockableScore) { }
481 /// Used only if an object of this type is returned as a trait impl by a method
482 pub(crate) extern "C" fn MultiThreadedLockableScore_free_void(this_ptr: *mut c_void) {
483 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeMultiThreadedLockableScore) };
486 impl MultiThreadedLockableScore {
487 pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedLockableScore {
488 unsafe { &*ObjOps::untweak_ptr(self.inner) }
490 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedLockableScore {
491 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
493 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
494 pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedLockableScore {
495 assert!(self.is_owned);
496 let ret = ObjOps::untweak_ptr(self.inner);
497 self.inner = core::ptr::null_mut();
501 impl From<nativeMultiThreadedLockableScore> for crate::lightning::routing::scoring::LockableScore {
502 fn from(obj: nativeMultiThreadedLockableScore) -> Self {
503 let rust_obj = crate::lightning::routing::scoring::MultiThreadedLockableScore { inner: ObjOps::heap_alloc(obj), is_owned: true };
504 let mut ret = MultiThreadedLockableScore_as_LockableScore(&rust_obj);
505 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
506 core::mem::forget(rust_obj);
507 ret.free = Some(MultiThreadedLockableScore_free_void);
511 /// Constructs a new LockableScore which calls the relevant methods on this_arg.
512 /// This copies the `inner` pointer in this_arg and thus the returned LockableScore must be freed before this_arg is
514 pub extern "C" fn MultiThreadedLockableScore_as_LockableScore(this_arg: &MultiThreadedLockableScore) -> crate::lightning::routing::scoring::LockableScore {
515 crate::lightning::routing::scoring::LockableScore {
516 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
518 read_lock: MultiThreadedLockableScore_LockableScore_read_lock,
519 write_lock: MultiThreadedLockableScore_LockableScore_write_lock,
524 extern "C" fn MultiThreadedLockableScore_LockableScore_read_lock(this_arg: *const c_void) -> crate::lightning::routing::scoring::ScoreLookUp {
525 let mut ret = <nativeMultiThreadedLockableScore as lightning::routing::scoring::LockableScore<'_, >>::read_lock(unsafe { &mut *(this_arg as *mut nativeMultiThreadedLockableScore) }, );
529 extern "C" fn MultiThreadedLockableScore_LockableScore_write_lock(this_arg: *const c_void) -> crate::lightning::routing::scoring::ScoreUpdate {
530 let mut ret = <nativeMultiThreadedLockableScore as lightning::routing::scoring::LockableScore<'_, >>::write_lock(unsafe { &mut *(this_arg as *mut nativeMultiThreadedLockableScore) }, );
535 /// Serialize the MultiThreadedLockableScore object into a byte array which can be read by MultiThreadedLockableScore_read
536 pub extern "C" fn MultiThreadedLockableScore_write(obj: &crate::lightning::routing::scoring::MultiThreadedLockableScore) -> crate::c_types::derived::CVec_u8Z {
537 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
540 pub(crate) extern "C" fn MultiThreadedLockableScore_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
541 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeMultiThreadedLockableScore) })
543 impl From<nativeMultiThreadedLockableScore> for crate::lightning::routing::scoring::WriteableScore {
544 fn from(obj: nativeMultiThreadedLockableScore) -> Self {
545 let rust_obj = crate::lightning::routing::scoring::MultiThreadedLockableScore { inner: ObjOps::heap_alloc(obj), is_owned: true };
546 let mut ret = MultiThreadedLockableScore_as_WriteableScore(&rust_obj);
547 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
548 core::mem::forget(rust_obj);
549 ret.free = Some(MultiThreadedLockableScore_free_void);
553 /// Constructs a new WriteableScore which calls the relevant methods on this_arg.
554 /// This copies the `inner` pointer in this_arg and thus the returned WriteableScore must be freed before this_arg is
556 pub extern "C" fn MultiThreadedLockableScore_as_WriteableScore(this_arg: &MultiThreadedLockableScore) -> crate::lightning::routing::scoring::WriteableScore {
557 crate::lightning::routing::scoring::WriteableScore {
558 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
560 LockableScore: crate::lightning::routing::scoring::LockableScore {
561 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
563 read_lock: MultiThreadedLockableScore_LockableScore_read_lock,
564 write_lock: MultiThreadedLockableScore_LockableScore_write_lock,
566 write: MultiThreadedLockableScore_write_void,
571 /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
574 pub extern "C" fn MultiThreadedLockableScore_new(mut score: crate::lightning::routing::scoring::Score) -> crate::lightning::routing::scoring::MultiThreadedLockableScore {
575 let mut ret = lightning::routing::scoring::MultiThreadedLockableScore::new(score);
576 crate::lightning::routing::scoring::MultiThreadedLockableScore { inner: ObjOps::heap_alloc(ret), is_owned: true }
580 use lightning::routing::scoring::MultiThreadedScoreLockRead as nativeMultiThreadedScoreLockReadImport;
581 pub(crate) type nativeMultiThreadedScoreLockRead = nativeMultiThreadedScoreLockReadImport<'static, crate::lightning::routing::scoring::Score, >;
583 /// A locked `MultiThreadedLockableScore`.
586 pub struct MultiThreadedScoreLockRead {
587 /// A pointer to the opaque Rust object.
589 /// Nearly everywhere, inner must be non-null, however in places where
590 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
591 pub inner: *mut nativeMultiThreadedScoreLockRead,
592 /// Indicates that this is the only struct which contains the same pointer.
594 /// Rust functions which take ownership of an object provided via an argument require
595 /// this to be true and invalidate the object pointed to by inner.
599 impl Drop for MultiThreadedScoreLockRead {
601 if self.is_owned && !<*mut nativeMultiThreadedScoreLockRead>::is_null(self.inner) {
602 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
606 /// Frees any resources used by the MultiThreadedScoreLockRead, if is_owned is set and inner is non-NULL.
608 pub extern "C" fn MultiThreadedScoreLockRead_free(this_obj: MultiThreadedScoreLockRead) { }
610 /// Used only if an object of this type is returned as a trait impl by a method
611 pub(crate) extern "C" fn MultiThreadedScoreLockRead_free_void(this_ptr: *mut c_void) {
612 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeMultiThreadedScoreLockRead) };
615 impl MultiThreadedScoreLockRead {
616 pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedScoreLockRead {
617 unsafe { &*ObjOps::untweak_ptr(self.inner) }
619 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedScoreLockRead {
620 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
622 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
623 pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedScoreLockRead {
624 assert!(self.is_owned);
625 let ret = ObjOps::untweak_ptr(self.inner);
626 self.inner = core::ptr::null_mut();
631 use lightning::routing::scoring::MultiThreadedScoreLockWrite as nativeMultiThreadedScoreLockWriteImport;
632 pub(crate) type nativeMultiThreadedScoreLockWrite = nativeMultiThreadedScoreLockWriteImport<'static, crate::lightning::routing::scoring::Score, >;
634 /// A locked `MultiThreadedLockableScore`.
637 pub struct MultiThreadedScoreLockWrite {
638 /// A pointer to the opaque Rust object.
640 /// Nearly everywhere, inner must be non-null, however in places where
641 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
642 pub inner: *mut nativeMultiThreadedScoreLockWrite,
643 /// Indicates that this is the only struct which contains the same pointer.
645 /// Rust functions which take ownership of an object provided via an argument require
646 /// this to be true and invalidate the object pointed to by inner.
650 impl Drop for MultiThreadedScoreLockWrite {
652 if self.is_owned && !<*mut nativeMultiThreadedScoreLockWrite>::is_null(self.inner) {
653 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
657 /// Frees any resources used by the MultiThreadedScoreLockWrite, if is_owned is set and inner is non-NULL.
659 pub extern "C" fn MultiThreadedScoreLockWrite_free(this_obj: MultiThreadedScoreLockWrite) { }
661 /// Used only if an object of this type is returned as a trait impl by a method
662 pub(crate) extern "C" fn MultiThreadedScoreLockWrite_free_void(this_ptr: *mut c_void) {
663 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeMultiThreadedScoreLockWrite) };
666 impl MultiThreadedScoreLockWrite {
667 pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedScoreLockWrite {
668 unsafe { &*ObjOps::untweak_ptr(self.inner) }
670 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedScoreLockWrite {
671 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
673 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
674 pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedScoreLockWrite {
675 assert!(self.is_owned);
676 let ret = ObjOps::untweak_ptr(self.inner);
677 self.inner = core::ptr::null_mut();
681 impl From<nativeMultiThreadedScoreLockRead> for crate::lightning::routing::scoring::ScoreLookUp {
682 fn from(obj: nativeMultiThreadedScoreLockRead) -> Self {
683 let rust_obj = crate::lightning::routing::scoring::MultiThreadedScoreLockRead { inner: ObjOps::heap_alloc(obj), is_owned: true };
684 let mut ret = MultiThreadedScoreLockRead_as_ScoreLookUp(&rust_obj);
685 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
686 core::mem::forget(rust_obj);
687 ret.free = Some(MultiThreadedScoreLockRead_free_void);
691 /// Constructs a new ScoreLookUp which calls the relevant methods on this_arg.
692 /// This copies the `inner` pointer in this_arg and thus the returned ScoreLookUp must be freed before this_arg is
694 pub extern "C" fn MultiThreadedScoreLockRead_as_ScoreLookUp(this_arg: &MultiThreadedScoreLockRead) -> crate::lightning::routing::scoring::ScoreLookUp {
695 crate::lightning::routing::scoring::ScoreLookUp {
696 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
698 channel_penalty_msat: MultiThreadedScoreLockRead_ScoreLookUp_channel_penalty_msat,
703 extern "C" fn MultiThreadedScoreLockRead_ScoreLookUp_channel_penalty_msat(this_arg: *const c_void, candidate: &crate::lightning::routing::router::CandidateRouteHop, mut usage: crate::lightning::routing::scoring::ChannelUsage, score_params: &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
704 let mut ret = <nativeMultiThreadedScoreLockRead as lightning::routing::scoring::ScoreLookUp>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLockRead) }, &candidate.to_native(), *unsafe { Box::from_raw(usage.take_inner()) }, score_params.get_native_ref());
709 /// Serialize the MultiThreadedScoreLockWrite object into a byte array which can be read by MultiThreadedScoreLockWrite_read
710 pub extern "C" fn MultiThreadedScoreLockWrite_write(obj: &crate::lightning::routing::scoring::MultiThreadedScoreLockWrite) -> crate::c_types::derived::CVec_u8Z {
711 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
714 pub(crate) extern "C" fn MultiThreadedScoreLockWrite_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
715 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeMultiThreadedScoreLockWrite) })
717 impl From<nativeMultiThreadedScoreLockWrite> for crate::lightning::routing::scoring::ScoreUpdate {
718 fn from(obj: nativeMultiThreadedScoreLockWrite) -> Self {
719 let rust_obj = crate::lightning::routing::scoring::MultiThreadedScoreLockWrite { inner: ObjOps::heap_alloc(obj), is_owned: true };
720 let mut ret = MultiThreadedScoreLockWrite_as_ScoreUpdate(&rust_obj);
721 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
722 core::mem::forget(rust_obj);
723 ret.free = Some(MultiThreadedScoreLockWrite_free_void);
727 /// Constructs a new ScoreUpdate which calls the relevant methods on this_arg.
728 /// This copies the `inner` pointer in this_arg and thus the returned ScoreUpdate must be freed before this_arg is
730 pub extern "C" fn MultiThreadedScoreLockWrite_as_ScoreUpdate(this_arg: &MultiThreadedScoreLockWrite) -> crate::lightning::routing::scoring::ScoreUpdate {
731 crate::lightning::routing::scoring::ScoreUpdate {
732 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
734 payment_path_failed: MultiThreadedScoreLockWrite_ScoreUpdate_payment_path_failed,
735 payment_path_successful: MultiThreadedScoreLockWrite_ScoreUpdate_payment_path_successful,
736 probe_failed: MultiThreadedScoreLockWrite_ScoreUpdate_probe_failed,
737 probe_successful: MultiThreadedScoreLockWrite_ScoreUpdate_probe_successful,
738 time_passed: MultiThreadedScoreLockWrite_ScoreUpdate_time_passed,
742 extern "C" fn MultiThreadedScoreLockWrite_ScoreUpdate_payment_path_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64, mut duration_since_epoch: u64) {
743 <nativeMultiThreadedScoreLockWrite as lightning::routing::scoring::ScoreUpdate>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLockWrite) }, path.get_native_ref(), short_channel_id, core::time::Duration::from_secs(duration_since_epoch))
745 extern "C" fn MultiThreadedScoreLockWrite_ScoreUpdate_payment_path_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut duration_since_epoch: u64) {
746 <nativeMultiThreadedScoreLockWrite as lightning::routing::scoring::ScoreUpdate>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLockWrite) }, path.get_native_ref(), core::time::Duration::from_secs(duration_since_epoch))
748 extern "C" fn MultiThreadedScoreLockWrite_ScoreUpdate_probe_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64, mut duration_since_epoch: u64) {
749 <nativeMultiThreadedScoreLockWrite as lightning::routing::scoring::ScoreUpdate>::probe_failed(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLockWrite) }, path.get_native_ref(), short_channel_id, core::time::Duration::from_secs(duration_since_epoch))
751 extern "C" fn MultiThreadedScoreLockWrite_ScoreUpdate_probe_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut duration_since_epoch: u64) {
752 <nativeMultiThreadedScoreLockWrite as lightning::routing::scoring::ScoreUpdate>::probe_successful(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLockWrite) }, path.get_native_ref(), core::time::Duration::from_secs(duration_since_epoch))
754 extern "C" fn MultiThreadedScoreLockWrite_ScoreUpdate_time_passed(this_arg: *mut c_void, mut duration_since_epoch: u64) {
755 <nativeMultiThreadedScoreLockWrite as lightning::routing::scoring::ScoreUpdate>::time_passed(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLockWrite) }, core::time::Duration::from_secs(duration_since_epoch))
759 use lightning::routing::scoring::ChannelUsage as nativeChannelUsageImport;
760 pub(crate) type nativeChannelUsage = nativeChannelUsageImport;
762 /// Proposed use of a channel passed as a parameter to [`ScoreLookUp::channel_penalty_msat`].
765 pub struct ChannelUsage {
766 /// A pointer to the opaque Rust object.
768 /// Nearly everywhere, inner must be non-null, however in places where
769 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
770 pub inner: *mut nativeChannelUsage,
771 /// Indicates that this is the only struct which contains the same pointer.
773 /// Rust functions which take ownership of an object provided via an argument require
774 /// this to be true and invalidate the object pointed to by inner.
778 impl Drop for ChannelUsage {
780 if self.is_owned && !<*mut nativeChannelUsage>::is_null(self.inner) {
781 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
785 /// Frees any resources used by the ChannelUsage, if is_owned is set and inner is non-NULL.
787 pub extern "C" fn ChannelUsage_free(this_obj: ChannelUsage) { }
789 /// Used only if an object of this type is returned as a trait impl by a method
790 pub(crate) extern "C" fn ChannelUsage_free_void(this_ptr: *mut c_void) {
791 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChannelUsage) };
795 pub(crate) fn get_native_ref(&self) -> &'static nativeChannelUsage {
796 unsafe { &*ObjOps::untweak_ptr(self.inner) }
798 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelUsage {
799 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
801 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
802 pub(crate) fn take_inner(mut self) -> *mut nativeChannelUsage {
803 assert!(self.is_owned);
804 let ret = ObjOps::untweak_ptr(self.inner);
805 self.inner = core::ptr::null_mut();
809 /// The amount to send through the channel, denominated in millisatoshis.
811 pub extern "C" fn ChannelUsage_get_amount_msat(this_ptr: &ChannelUsage) -> u64 {
812 let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_msat;
815 /// The amount to send through the channel, denominated in millisatoshis.
817 pub extern "C" fn ChannelUsage_set_amount_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
818 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_msat = val;
820 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
821 /// as part of a multi-path payment.
823 pub extern "C" fn ChannelUsage_get_inflight_htlc_msat(this_ptr: &ChannelUsage) -> u64 {
824 let mut inner_val = &mut this_ptr.get_native_mut_ref().inflight_htlc_msat;
827 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
828 /// as part of a multi-path payment.
830 pub extern "C" fn ChannelUsage_set_inflight_htlc_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
831 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inflight_htlc_msat = val;
833 /// The effective capacity of the channel.
835 pub extern "C" fn ChannelUsage_get_effective_capacity(this_ptr: &ChannelUsage) -> crate::lightning::routing::gossip::EffectiveCapacity {
836 let mut inner_val = &mut this_ptr.get_native_mut_ref().effective_capacity;
837 crate::lightning::routing::gossip::EffectiveCapacity::from_native(inner_val)
839 /// The effective capacity of the channel.
841 pub extern "C" fn ChannelUsage_set_effective_capacity(this_ptr: &mut ChannelUsage, mut val: crate::lightning::routing::gossip::EffectiveCapacity) {
842 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.effective_capacity = val.into_native();
844 /// Constructs a new ChannelUsage given each field
847 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 {
848 ChannelUsage { inner: ObjOps::heap_alloc(nativeChannelUsage {
849 amount_msat: amount_msat_arg,
850 inflight_htlc_msat: inflight_htlc_msat_arg,
851 effective_capacity: effective_capacity_arg.into_native(),
854 impl Clone for ChannelUsage {
855 fn clone(&self) -> Self {
857 inner: if <*mut nativeChannelUsage>::is_null(self.inner) { core::ptr::null_mut() } else {
858 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
864 /// Used only if an object of this type is returned as a trait impl by a method
865 pub(crate) extern "C" fn ChannelUsage_clone_void(this_ptr: *const c_void) -> *mut c_void {
866 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeChannelUsage)).clone() })) as *mut c_void
869 /// Creates a copy of the ChannelUsage
870 pub extern "C" fn ChannelUsage_clone(orig: &ChannelUsage) -> ChannelUsage {
873 /// Get a string which allows debug introspection of a ChannelUsage object
874 pub extern "C" fn ChannelUsage_debug_str_void(o: *const c_void) -> Str {
875 alloc::format!("{:?}", unsafe { o as *const crate::lightning::routing::scoring::ChannelUsage }).into()}
877 use lightning::routing::scoring::FixedPenaltyScorer as nativeFixedPenaltyScorerImport;
878 pub(crate) type nativeFixedPenaltyScorer = nativeFixedPenaltyScorerImport;
880 /// [`ScoreLookUp`] implementation that uses a fixed penalty.
883 pub struct FixedPenaltyScorer {
884 /// A pointer to the opaque Rust object.
886 /// Nearly everywhere, inner must be non-null, however in places where
887 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
888 pub inner: *mut nativeFixedPenaltyScorer,
889 /// Indicates that this is the only struct which contains the same pointer.
891 /// Rust functions which take ownership of an object provided via an argument require
892 /// this to be true and invalidate the object pointed to by inner.
896 impl Drop for FixedPenaltyScorer {
898 if self.is_owned && !<*mut nativeFixedPenaltyScorer>::is_null(self.inner) {
899 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
903 /// Frees any resources used by the FixedPenaltyScorer, if is_owned is set and inner is non-NULL.
905 pub extern "C" fn FixedPenaltyScorer_free(this_obj: FixedPenaltyScorer) { }
907 /// Used only if an object of this type is returned as a trait impl by a method
908 pub(crate) extern "C" fn FixedPenaltyScorer_free_void(this_ptr: *mut c_void) {
909 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeFixedPenaltyScorer) };
912 impl FixedPenaltyScorer {
913 pub(crate) fn get_native_ref(&self) -> &'static nativeFixedPenaltyScorer {
914 unsafe { &*ObjOps::untweak_ptr(self.inner) }
916 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFixedPenaltyScorer {
917 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
919 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
920 pub(crate) fn take_inner(mut self) -> *mut nativeFixedPenaltyScorer {
921 assert!(self.is_owned);
922 let ret = ObjOps::untweak_ptr(self.inner);
923 self.inner = core::ptr::null_mut();
927 impl Clone for FixedPenaltyScorer {
928 fn clone(&self) -> Self {
930 inner: if <*mut nativeFixedPenaltyScorer>::is_null(self.inner) { core::ptr::null_mut() } else {
931 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
937 /// Used only if an object of this type is returned as a trait impl by a method
938 pub(crate) extern "C" fn FixedPenaltyScorer_clone_void(this_ptr: *const c_void) -> *mut c_void {
939 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeFixedPenaltyScorer)).clone() })) as *mut c_void
942 /// Creates a copy of the FixedPenaltyScorer
943 pub extern "C" fn FixedPenaltyScorer_clone(orig: &FixedPenaltyScorer) -> FixedPenaltyScorer {
946 /// Creates a new scorer using `penalty_msat`.
949 pub extern "C" fn FixedPenaltyScorer_with_penalty(mut penalty_msat: u64) -> crate::lightning::routing::scoring::FixedPenaltyScorer {
950 let mut ret = lightning::routing::scoring::FixedPenaltyScorer::with_penalty(penalty_msat);
951 crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
954 impl From<nativeFixedPenaltyScorer> for crate::lightning::routing::scoring::ScoreLookUp {
955 fn from(obj: nativeFixedPenaltyScorer) -> Self {
956 let rust_obj = crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
957 let mut ret = FixedPenaltyScorer_as_ScoreLookUp(&rust_obj);
958 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
959 core::mem::forget(rust_obj);
960 ret.free = Some(FixedPenaltyScorer_free_void);
964 /// Constructs a new ScoreLookUp which calls the relevant methods on this_arg.
965 /// This copies the `inner` pointer in this_arg and thus the returned ScoreLookUp must be freed before this_arg is
967 pub extern "C" fn FixedPenaltyScorer_as_ScoreLookUp(this_arg: &FixedPenaltyScorer) -> crate::lightning::routing::scoring::ScoreLookUp {
968 crate::lightning::routing::scoring::ScoreLookUp {
969 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
971 channel_penalty_msat: FixedPenaltyScorer_ScoreLookUp_channel_penalty_msat,
976 extern "C" fn FixedPenaltyScorer_ScoreLookUp_channel_penalty_msat(this_arg: *const c_void, candidate: &crate::lightning::routing::router::CandidateRouteHop, mut usage: crate::lightning::routing::scoring::ChannelUsage, score_params: &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
977 let mut ret = <nativeFixedPenaltyScorer as lightning::routing::scoring::ScoreLookUp>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &candidate.to_native(), *unsafe { Box::from_raw(usage.take_inner()) }, score_params.get_native_ref());
981 impl From<nativeFixedPenaltyScorer> for crate::lightning::routing::scoring::ScoreUpdate {
982 fn from(obj: nativeFixedPenaltyScorer) -> Self {
983 let rust_obj = crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
984 let mut ret = FixedPenaltyScorer_as_ScoreUpdate(&rust_obj);
985 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
986 core::mem::forget(rust_obj);
987 ret.free = Some(FixedPenaltyScorer_free_void);
991 /// Constructs a new ScoreUpdate which calls the relevant methods on this_arg.
992 /// This copies the `inner` pointer in this_arg and thus the returned ScoreUpdate must be freed before this_arg is
994 pub extern "C" fn FixedPenaltyScorer_as_ScoreUpdate(this_arg: &FixedPenaltyScorer) -> crate::lightning::routing::scoring::ScoreUpdate {
995 crate::lightning::routing::scoring::ScoreUpdate {
996 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
998 payment_path_failed: FixedPenaltyScorer_ScoreUpdate_payment_path_failed,
999 payment_path_successful: FixedPenaltyScorer_ScoreUpdate_payment_path_successful,
1000 probe_failed: FixedPenaltyScorer_ScoreUpdate_probe_failed,
1001 probe_successful: FixedPenaltyScorer_ScoreUpdate_probe_successful,
1002 time_passed: FixedPenaltyScorer_ScoreUpdate_time_passed,
1006 extern "C" fn FixedPenaltyScorer_ScoreUpdate_payment_path_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64, mut duration_since_epoch: u64) {
1007 <nativeFixedPenaltyScorer as lightning::routing::scoring::ScoreUpdate>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref(), short_channel_id, core::time::Duration::from_secs(duration_since_epoch))
1009 extern "C" fn FixedPenaltyScorer_ScoreUpdate_payment_path_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut duration_since_epoch: u64) {
1010 <nativeFixedPenaltyScorer as lightning::routing::scoring::ScoreUpdate>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref(), core::time::Duration::from_secs(duration_since_epoch))
1012 extern "C" fn FixedPenaltyScorer_ScoreUpdate_probe_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64, mut duration_since_epoch: u64) {
1013 <nativeFixedPenaltyScorer as lightning::routing::scoring::ScoreUpdate>::probe_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref(), short_channel_id, core::time::Duration::from_secs(duration_since_epoch))
1015 extern "C" fn FixedPenaltyScorer_ScoreUpdate_probe_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut duration_since_epoch: u64) {
1016 <nativeFixedPenaltyScorer as lightning::routing::scoring::ScoreUpdate>::probe_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref(), core::time::Duration::from_secs(duration_since_epoch))
1018 extern "C" fn FixedPenaltyScorer_ScoreUpdate_time_passed(this_arg: *mut c_void, mut duration_since_epoch: u64) {
1019 <nativeFixedPenaltyScorer as lightning::routing::scoring::ScoreUpdate>::time_passed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, core::time::Duration::from_secs(duration_since_epoch))
1023 /// Serialize the FixedPenaltyScorer object into a byte array which can be read by FixedPenaltyScorer_read
1024 pub extern "C" fn FixedPenaltyScorer_write(obj: &crate::lightning::routing::scoring::FixedPenaltyScorer) -> crate::c_types::derived::CVec_u8Z {
1025 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
1028 pub(crate) extern "C" fn FixedPenaltyScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
1029 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFixedPenaltyScorer) })
1032 /// Read a FixedPenaltyScorer from a byte array, created by FixedPenaltyScorer_write
1033 pub extern "C" fn FixedPenaltyScorer_read(ser: crate::c_types::u8slice, arg: u64) -> crate::c_types::derived::CResult_FixedPenaltyScorerDecodeErrorZ {
1035 let res: Result<lightning::routing::scoring::FixedPenaltyScorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
1036 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() };
1040 use lightning::routing::scoring::ProbabilisticScorer as nativeProbabilisticScorerImport;
1041 pub(crate) type nativeProbabilisticScorer = nativeProbabilisticScorerImport<&'static lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger, >;
1043 /// [`ScoreLookUp`] implementation using channel success probability distributions.
1045 /// Channels are tracked with upper and lower liquidity bounds - when an HTLC fails at a channel,
1046 /// we learn that the upper-bound on the available liquidity is lower than the amount of the HTLC.
1047 /// When a payment is forwarded through a channel (but fails later in the route), we learn the
1048 /// lower-bound on the channel's available liquidity must be at least the value of the HTLC.
1050 /// These bounds are then used to determine a success probability using the formula from
1051 /// *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
1052 /// and Stefan Richter [[1]] (i.e. `(upper_bound - payment_amount) / (upper_bound - lower_bound)`).
1054 /// This probability is combined with the [`liquidity_penalty_multiplier_msat`] and
1055 /// [`liquidity_penalty_amount_multiplier_msat`] parameters to calculate a concrete penalty in
1056 /// milli-satoshis. The penalties, when added across all hops, have the property of being linear in
1057 /// terms of the entire path's success probability. This allows the router to directly compare
1058 /// penalties for different paths. See the documentation of those parameters for the exact formulas.
1060 /// The liquidity bounds are decayed by halving them every [`liquidity_offset_half_life`].
1062 /// Further, we track the history of our upper and lower liquidity bounds for each channel,
1063 /// allowing us to assign a second penalty (using [`historical_liquidity_penalty_multiplier_msat`]
1064 /// and [`historical_liquidity_penalty_amount_multiplier_msat`]) based on the same probability
1065 /// formula, but using the history of a channel rather than our latest estimates for the liquidity
1068 /// [1]: https://arxiv.org/abs/2107.05322
1069 /// [`liquidity_penalty_multiplier_msat`]: ProbabilisticScoringFeeParameters::liquidity_penalty_multiplier_msat
1070 /// [`liquidity_penalty_amount_multiplier_msat`]: ProbabilisticScoringFeeParameters::liquidity_penalty_amount_multiplier_msat
1071 /// [`liquidity_offset_half_life`]: ProbabilisticScoringDecayParameters::liquidity_offset_half_life
1072 /// [`historical_liquidity_penalty_multiplier_msat`]: ProbabilisticScoringFeeParameters::historical_liquidity_penalty_multiplier_msat
1073 /// [`historical_liquidity_penalty_amount_multiplier_msat`]: ProbabilisticScoringFeeParameters::historical_liquidity_penalty_amount_multiplier_msat
1076 pub struct ProbabilisticScorer {
1077 /// A pointer to the opaque Rust object.
1079 /// Nearly everywhere, inner must be non-null, however in places where
1080 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
1081 pub inner: *mut nativeProbabilisticScorer,
1082 /// Indicates that this is the only struct which contains the same pointer.
1084 /// Rust functions which take ownership of an object provided via an argument require
1085 /// this to be true and invalidate the object pointed to by inner.
1089 impl Drop for ProbabilisticScorer {
1090 fn drop(&mut self) {
1091 if self.is_owned && !<*mut nativeProbabilisticScorer>::is_null(self.inner) {
1092 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
1096 /// Frees any resources used by the ProbabilisticScorer, if is_owned is set and inner is non-NULL.
1098 pub extern "C" fn ProbabilisticScorer_free(this_obj: ProbabilisticScorer) { }
1100 /// Used only if an object of this type is returned as a trait impl by a method
1101 pub(crate) extern "C" fn ProbabilisticScorer_free_void(this_ptr: *mut c_void) {
1102 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeProbabilisticScorer) };
1105 impl ProbabilisticScorer {
1106 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScorer {
1107 unsafe { &*ObjOps::untweak_ptr(self.inner) }
1109 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScorer {
1110 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
1112 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
1113 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScorer {
1114 assert!(self.is_owned);
1115 let ret = ObjOps::untweak_ptr(self.inner);
1116 self.inner = core::ptr::null_mut();
1121 use lightning::routing::scoring::ProbabilisticScoringFeeParameters as nativeProbabilisticScoringFeeParametersImport;
1122 pub(crate) type nativeProbabilisticScoringFeeParameters = nativeProbabilisticScoringFeeParametersImport;
1124 /// Parameters for configuring [`ProbabilisticScorer`].
1126 /// Used to configure base, liquidity, and amount penalties, the sum of which comprises the channel
1127 /// penalty (i.e., the amount in msats willing to be paid to avoid routing through the channel).
1129 /// The penalty applied to any channel by the [`ProbabilisticScorer`] is the sum of each of the
1130 /// parameters here.
1133 pub struct ProbabilisticScoringFeeParameters {
1134 /// A pointer to the opaque Rust object.
1136 /// Nearly everywhere, inner must be non-null, however in places where
1137 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
1138 pub inner: *mut nativeProbabilisticScoringFeeParameters,
1139 /// Indicates that this is the only struct which contains the same pointer.
1141 /// Rust functions which take ownership of an object provided via an argument require
1142 /// this to be true and invalidate the object pointed to by inner.
1146 impl Drop for ProbabilisticScoringFeeParameters {
1147 fn drop(&mut self) {
1148 if self.is_owned && !<*mut nativeProbabilisticScoringFeeParameters>::is_null(self.inner) {
1149 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
1153 /// Frees any resources used by the ProbabilisticScoringFeeParameters, if is_owned is set and inner is non-NULL.
1155 pub extern "C" fn ProbabilisticScoringFeeParameters_free(this_obj: ProbabilisticScoringFeeParameters) { }
1157 /// Used only if an object of this type is returned as a trait impl by a method
1158 pub(crate) extern "C" fn ProbabilisticScoringFeeParameters_free_void(this_ptr: *mut c_void) {
1159 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeProbabilisticScoringFeeParameters) };
1162 impl ProbabilisticScoringFeeParameters {
1163 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringFeeParameters {
1164 unsafe { &*ObjOps::untweak_ptr(self.inner) }
1166 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringFeeParameters {
1167 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
1169 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
1170 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringFeeParameters {
1171 assert!(self.is_owned);
1172 let ret = ObjOps::untweak_ptr(self.inner);
1173 self.inner = core::ptr::null_mut();
1177 /// A fixed penalty in msats to apply to each channel.
1179 /// Default value: 500 msat
1181 pub extern "C" fn ProbabilisticScoringFeeParameters_get_base_penalty_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1182 let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
1185 /// A fixed penalty in msats to apply to each channel.
1187 /// Default value: 500 msat
1189 pub extern "C" fn ProbabilisticScoringFeeParameters_set_base_penalty_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1190 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
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_get_base_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1207 let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_amount_multiplier_msat;
1210 /// A multiplier used with the total amount flowing over a channel to calculate a fixed penalty
1211 /// applied to each channel, in excess of the [`base_penalty_msat`].
1213 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
1214 /// fees plus penalty) for large payments. The penalty is computed as the product of this
1215 /// multiplier and `2^30`ths of the total amount flowing over a channel (i.e. the payment
1216 /// amount plus the amount of any other HTLCs flowing we sent over the same channel).
1218 /// ie `base_penalty_amount_multiplier_msat * amount_msat / 2^30`
1220 /// Default value: 8,192 msat
1222 /// [`base_penalty_msat`]: Self::base_penalty_msat
1224 pub extern "C" fn ProbabilisticScoringFeeParameters_set_base_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1225 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_amount_multiplier_msat = val;
1227 /// A multiplier used in conjunction with the negative `log10` of the channel's success
1228 /// probability for a payment, as determined by our latest estimates of the channel's
1229 /// liquidity, to determine the liquidity penalty.
1231 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
1232 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
1233 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
1234 /// lower bounding the success probability to `0.01`) when the amount falls within the
1235 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
1236 /// result in a `u64::max_value` penalty, however.
1238 /// `-log10(success_probability) * liquidity_penalty_multiplier_msat`
1240 /// Default value: 30,000 msat
1242 /// [`liquidity_offset_half_life`]: ProbabilisticScoringDecayParameters::liquidity_offset_half_life
1244 pub extern "C" fn ProbabilisticScoringFeeParameters_get_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1245 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_multiplier_msat;
1248 /// A multiplier used in conjunction with the negative `log10` of the channel's success
1249 /// probability for a payment, as determined by our latest estimates of the channel's
1250 /// liquidity, to determine the liquidity penalty.
1252 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
1253 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
1254 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
1255 /// lower bounding the success probability to `0.01`) when the amount falls within the
1256 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
1257 /// result in a `u64::max_value` penalty, however.
1259 /// `-log10(success_probability) * liquidity_penalty_multiplier_msat`
1261 /// Default value: 30,000 msat
1263 /// [`liquidity_offset_half_life`]: ProbabilisticScoringDecayParameters::liquidity_offset_half_life
1265 pub extern "C" fn ProbabilisticScoringFeeParameters_set_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1266 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_multiplier_msat = val;
1268 /// A multiplier used in conjunction with the total amount flowing over a channel and the
1269 /// negative `log10` of the channel's success probability for the payment, as determined by our
1270 /// latest estimates of the channel's liquidity, to determine the amount penalty.
1272 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
1273 /// fees plus penalty) for large payments. The penalty is computed as the product of this
1274 /// multiplier and `2^20`ths of the amount flowing over this channel, weighted by the negative
1275 /// `log10` of the success probability.
1277 /// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
1279 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
1280 /// the amount will result in a penalty of the multiplier. And, as the success probability
1281 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
1282 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
1285 /// Default value: 192 msat
1287 pub extern "C" fn ProbabilisticScoringFeeParameters_get_liquidity_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1288 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_amount_multiplier_msat;
1291 /// A multiplier used in conjunction with the total amount flowing over a channel and the
1292 /// negative `log10` of the channel's success probability for the payment, as determined by our
1293 /// latest estimates of the channel's liquidity, to determine the amount penalty.
1295 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
1296 /// fees plus penalty) for large payments. The penalty is computed as the product of this
1297 /// multiplier and `2^20`ths of the amount flowing over this channel, weighted by the negative
1298 /// `log10` of the success probability.
1300 /// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
1302 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
1303 /// the amount will result in a penalty of the multiplier. And, as the success probability
1304 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
1305 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
1308 /// Default value: 192 msat
1310 pub extern "C" fn ProbabilisticScoringFeeParameters_set_liquidity_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1311 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_amount_multiplier_msat = val;
1313 /// A multiplier used in conjunction with the negative `log10` of the channel's success
1314 /// probability for the payment, as determined based on the history of our estimates of the
1315 /// channel's available liquidity, to determine a penalty.
1317 /// This penalty is similar to [`liquidity_penalty_multiplier_msat`], however, instead of using
1318 /// only our latest estimate for the current liquidity available in the channel, it estimates
1319 /// success probability based on the estimated liquidity available in the channel through
1320 /// history. Specifically, every time we update our liquidity bounds on a given channel, we
1321 /// track which of several buckets those bounds fall into, exponentially decaying the
1322 /// probability of each bucket as new samples are added.
1324 /// Default value: 10,000 msat
1326 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1328 pub extern "C" fn ProbabilisticScoringFeeParameters_get_historical_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1329 let mut inner_val = &mut this_ptr.get_native_mut_ref().historical_liquidity_penalty_multiplier_msat;
1332 /// A multiplier used in conjunction with the negative `log10` of the channel's success
1333 /// probability for the payment, as determined based on the history of our estimates of the
1334 /// channel's available liquidity, to determine a penalty.
1336 /// This penalty is similar to [`liquidity_penalty_multiplier_msat`], however, instead of using
1337 /// only our latest estimate for the current liquidity available in the channel, it estimates
1338 /// success probability based on the estimated liquidity available in the channel through
1339 /// history. Specifically, every time we update our liquidity bounds on a given channel, we
1340 /// track which of several buckets those bounds fall into, exponentially decaying the
1341 /// probability of each bucket as new samples are added.
1343 /// Default value: 10,000 msat
1345 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1347 pub extern "C" fn ProbabilisticScoringFeeParameters_set_historical_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1348 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.historical_liquidity_penalty_multiplier_msat = val;
1350 /// A multiplier used in conjunction with the total amount flowing over a channel and the
1351 /// negative `log10` of the channel's success probability for the payment, as determined based
1352 /// on the history of our estimates of the channel's available liquidity, to determine a
1355 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost for
1356 /// large payments. The penalty is computed as the product of this multiplier and `2^20`ths
1357 /// of the amount flowing over this channel, weighted by the negative `log10` of the success
1360 /// This penalty is similar to [`liquidity_penalty_amount_multiplier_msat`], however, instead
1361 /// of using only our latest estimate for the current liquidity available in the channel, it
1362 /// estimates success probability based on the estimated liquidity available in the channel
1363 /// through history. Specifically, every time we update our liquidity bounds on a given
1364 /// channel, we track which of several buckets those bounds fall into, exponentially decaying
1365 /// the probability of each bucket as new samples are added.
1367 /// Default value: 64 msat
1369 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1371 pub extern "C" fn ProbabilisticScoringFeeParameters_get_historical_liquidity_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1372 let mut inner_val = &mut this_ptr.get_native_mut_ref().historical_liquidity_penalty_amount_multiplier_msat;
1375 /// A multiplier used in conjunction with the total amount flowing over a channel and the
1376 /// negative `log10` of the channel's success probability for the payment, as determined based
1377 /// on the history of our estimates of the channel's available liquidity, to determine a
1380 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost for
1381 /// large payments. The penalty is computed as the product of this multiplier and `2^20`ths
1382 /// of the amount flowing over this channel, weighted by the negative `log10` of the success
1385 /// This penalty is similar to [`liquidity_penalty_amount_multiplier_msat`], however, instead
1386 /// of using only our latest estimate for the current liquidity available in the channel, it
1387 /// estimates success probability based on the estimated liquidity available in the channel
1388 /// through history. Specifically, every time we update our liquidity bounds on a given
1389 /// channel, we track which of several buckets those bounds fall into, exponentially decaying
1390 /// the probability of each bucket as new samples are added.
1392 /// Default value: 64 msat
1394 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1396 pub extern "C" fn ProbabilisticScoringFeeParameters_set_historical_liquidity_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1397 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.historical_liquidity_penalty_amount_multiplier_msat = val;
1399 /// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
1400 /// channel's capacity, (ie. htlc_maximum_msat >= 0.5 * channel_capacity) which makes us
1401 /// prefer nodes with a smaller `htlc_maximum_msat`. We treat such nodes preferentially
1402 /// as this makes balance discovery attacks harder to execute, thereby creating an incentive
1403 /// to restrict `htlc_maximum_msat` and improve privacy.
1405 /// Default value: 250 msat
1407 pub extern "C" fn ProbabilisticScoringFeeParameters_get_anti_probing_penalty_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1408 let mut inner_val = &mut this_ptr.get_native_mut_ref().anti_probing_penalty_msat;
1411 /// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
1412 /// channel's capacity, (ie. htlc_maximum_msat >= 0.5 * channel_capacity) which makes us
1413 /// prefer nodes with a smaller `htlc_maximum_msat`. We treat such nodes preferentially
1414 /// as this makes balance discovery attacks harder to execute, thereby creating an incentive
1415 /// to restrict `htlc_maximum_msat` and improve privacy.
1417 /// Default value: 250 msat
1419 pub extern "C" fn ProbabilisticScoringFeeParameters_set_anti_probing_penalty_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1420 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.anti_probing_penalty_msat = val;
1422 /// This penalty is applied when the total amount flowing over a channel exceeds our current
1423 /// estimate of the channel's available liquidity. The total amount is the amount of the
1424 /// current HTLC plus any HTLCs which we've sent over the same channel.
1426 /// Note that in this case all other penalties, including the
1427 /// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
1428 /// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
1429 /// applicable, are still included in the overall penalty.
1431 /// If you wish to avoid creating paths with such channels entirely, setting this to a value of
1432 /// `u64::max_value()` will guarantee that.
1434 /// Default value: 1_0000_0000_000 msat (1 Bitcoin)
1436 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1437 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1438 /// [`base_penalty_msat`]: Self::base_penalty_msat
1439 /// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
1441 pub extern "C" fn ProbabilisticScoringFeeParameters_get_considered_impossible_penalty_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1442 let mut inner_val = &mut this_ptr.get_native_mut_ref().considered_impossible_penalty_msat;
1445 /// This penalty is applied when the total amount flowing over a channel exceeds our current
1446 /// estimate of the channel's available liquidity. The total amount is the amount of the
1447 /// current HTLC plus any HTLCs which we've sent over the same channel.
1449 /// Note that in this case all other penalties, including the
1450 /// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
1451 /// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
1452 /// applicable, are still included in the overall penalty.
1454 /// If you wish to avoid creating paths with such channels entirely, setting this to a value of
1455 /// `u64::max_value()` will guarantee that.
1457 /// Default value: 1_0000_0000_000 msat (1 Bitcoin)
1459 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1460 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1461 /// [`base_penalty_msat`]: Self::base_penalty_msat
1462 /// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
1464 pub extern "C" fn ProbabilisticScoringFeeParameters_set_considered_impossible_penalty_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1465 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.considered_impossible_penalty_msat = val;
1467 /// In order to calculate most of the scores above, we must first convert a lower and upper
1468 /// bound on the available liquidity in a channel into the probability that we think a payment
1469 /// will succeed. That probability is derived from a Probability Density Function for where we
1470 /// think the liquidity in a channel likely lies, given such bounds.
1472 /// If this flag is set, that PDF is simply a constant - we assume that the actual available
1473 /// liquidity in a channel is just as likely to be at any point between our lower and upper
1476 /// If this flag is *not* set, that PDF is `(x - 0.5*capacity) ^ 2`. That is, we use an
1477 /// exponential curve which expects the liquidity of a channel to lie \"at the edges\". This
1478 /// matches experimental results - most routing nodes do not aggressively rebalance their
1479 /// channels and flows in the network are often unbalanced, leaving liquidity usually
1482 /// Thus, for the \"best\" routes, leave this flag `false`. However, the flag does imply a number
1483 /// of floating-point multiplications in the hottest routing code, which may lead to routing
1484 /// performance degradation on some machines.
1486 /// Default value: false
1488 pub extern "C" fn ProbabilisticScoringFeeParameters_get_linear_success_probability(this_ptr: &ProbabilisticScoringFeeParameters) -> bool {
1489 let mut inner_val = &mut this_ptr.get_native_mut_ref().linear_success_probability;
1492 /// In order to calculate most of the scores above, we must first convert a lower and upper
1493 /// bound on the available liquidity in a channel into the probability that we think a payment
1494 /// will succeed. That probability is derived from a Probability Density Function for where we
1495 /// think the liquidity in a channel likely lies, given such bounds.
1497 /// If this flag is set, that PDF is simply a constant - we assume that the actual available
1498 /// liquidity in a channel is just as likely to be at any point between our lower and upper
1501 /// If this flag is *not* set, that PDF is `(x - 0.5*capacity) ^ 2`. That is, we use an
1502 /// exponential curve which expects the liquidity of a channel to lie \"at the edges\". This
1503 /// matches experimental results - most routing nodes do not aggressively rebalance their
1504 /// channels and flows in the network are often unbalanced, leaving liquidity usually
1507 /// Thus, for the \"best\" routes, leave this flag `false`. However, the flag does imply a number
1508 /// of floating-point multiplications in the hottest routing code, which may lead to routing
1509 /// performance degradation on some machines.
1511 /// Default value: false
1513 pub extern "C" fn ProbabilisticScoringFeeParameters_set_linear_success_probability(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: bool) {
1514 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.linear_success_probability = val;
1516 impl Clone for ProbabilisticScoringFeeParameters {
1517 fn clone(&self) -> Self {
1519 inner: if <*mut nativeProbabilisticScoringFeeParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
1520 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
1526 /// Used only if an object of this type is returned as a trait impl by a method
1527 pub(crate) extern "C" fn ProbabilisticScoringFeeParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
1528 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeProbabilisticScoringFeeParameters)).clone() })) as *mut c_void
1531 /// Creates a copy of the ProbabilisticScoringFeeParameters
1532 pub extern "C" fn ProbabilisticScoringFeeParameters_clone(orig: &ProbabilisticScoringFeeParameters) -> ProbabilisticScoringFeeParameters {
1535 /// Creates a "default" ProbabilisticScoringFeeParameters. See struct and individual field documentaiton for details on which values are used.
1538 pub extern "C" fn ProbabilisticScoringFeeParameters_default() -> ProbabilisticScoringFeeParameters {
1539 ProbabilisticScoringFeeParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
1541 /// Marks the node with the given `node_id` as banned,
1542 /// i.e it will be avoided during path finding.
1544 pub extern "C" fn ProbabilisticScoringFeeParameters_add_banned(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters, node_id: &crate::lightning::routing::gossip::NodeId) {
1545 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.add_banned(node_id.get_native_ref())
1548 /// Marks all nodes in the given list as banned, i.e.,
1549 /// they will be avoided during path finding.
1551 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) {
1552 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()) } }); };
1553 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.add_banned_from_list(local_node_ids)
1556 /// Removes the node with the given `node_id` from the list of nodes to avoid.
1558 pub extern "C" fn ProbabilisticScoringFeeParameters_remove_banned(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters, node_id: &crate::lightning::routing::gossip::NodeId) {
1559 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.remove_banned(node_id.get_native_ref())
1562 /// Sets a manual penalty for the given node.
1564 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) {
1565 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.set_manual_penalty(node_id.get_native_ref(), penalty)
1568 /// Removes the node with the given `node_id` from the list of manual penalties.
1570 pub extern "C" fn ProbabilisticScoringFeeParameters_remove_manual_penalty(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters, node_id: &crate::lightning::routing::gossip::NodeId) {
1571 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.remove_manual_penalty(node_id.get_native_ref())
1574 /// Clears the list of manual penalties that are applied during path finding.
1576 pub extern "C" fn ProbabilisticScoringFeeParameters_clear_manual_penalties(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) {
1577 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.clear_manual_penalties()
1581 use lightning::routing::scoring::ProbabilisticScoringDecayParameters as nativeProbabilisticScoringDecayParametersImport;
1582 pub(crate) type nativeProbabilisticScoringDecayParameters = nativeProbabilisticScoringDecayParametersImport;
1584 /// Parameters for configuring [`ProbabilisticScorer`].
1586 /// Used to configure decay parameters that are static throughout the lifetime of the scorer.
1587 /// these decay parameters affect the score of the channel penalty and are not changed on a
1588 /// per-route penalty cost call.
1591 pub struct ProbabilisticScoringDecayParameters {
1592 /// A pointer to the opaque Rust object.
1594 /// Nearly everywhere, inner must be non-null, however in places where
1595 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
1596 pub inner: *mut nativeProbabilisticScoringDecayParameters,
1597 /// Indicates that this is the only struct which contains the same pointer.
1599 /// Rust functions which take ownership of an object provided via an argument require
1600 /// this to be true and invalidate the object pointed to by inner.
1604 impl Drop for ProbabilisticScoringDecayParameters {
1605 fn drop(&mut self) {
1606 if self.is_owned && !<*mut nativeProbabilisticScoringDecayParameters>::is_null(self.inner) {
1607 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
1611 /// Frees any resources used by the ProbabilisticScoringDecayParameters, if is_owned is set and inner is non-NULL.
1613 pub extern "C" fn ProbabilisticScoringDecayParameters_free(this_obj: ProbabilisticScoringDecayParameters) { }
1615 /// Used only if an object of this type is returned as a trait impl by a method
1616 pub(crate) extern "C" fn ProbabilisticScoringDecayParameters_free_void(this_ptr: *mut c_void) {
1617 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeProbabilisticScoringDecayParameters) };
1620 impl ProbabilisticScoringDecayParameters {
1621 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringDecayParameters {
1622 unsafe { &*ObjOps::untweak_ptr(self.inner) }
1624 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringDecayParameters {
1625 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
1627 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
1628 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringDecayParameters {
1629 assert!(self.is_owned);
1630 let ret = ObjOps::untweak_ptr(self.inner);
1631 self.inner = core::ptr::null_mut();
1635 /// If we aren't learning any new datapoints for a channel, the historical liquidity bounds
1636 /// tracking can simply live on with increasingly stale data. Instead, when a channel has not
1637 /// seen a liquidity estimate update for this amount of time, the historical datapoints are
1638 /// decayed by half.
1639 /// For an example of historical_no_updates_half_life being used see [`historical_estimated_channel_liquidity_probabilities`]
1641 /// Note that after 16 or more half lives all historical data will be completely gone.
1643 /// Default value: 14 days
1645 /// [`historical_estimated_channel_liquidity_probabilities`]: ProbabilisticScorer::historical_estimated_channel_liquidity_probabilities
1647 pub extern "C" fn ProbabilisticScoringDecayParameters_get_historical_no_updates_half_life(this_ptr: &ProbabilisticScoringDecayParameters) -> u64 {
1648 let mut inner_val = &mut this_ptr.get_native_mut_ref().historical_no_updates_half_life;
1651 /// If we aren't learning any new datapoints for a channel, the historical liquidity bounds
1652 /// tracking can simply live on with increasingly stale data. Instead, when a channel has not
1653 /// seen a liquidity estimate update for this amount of time, the historical datapoints are
1654 /// decayed by half.
1655 /// For an example of historical_no_updates_half_life being used see [`historical_estimated_channel_liquidity_probabilities`]
1657 /// Note that after 16 or more half lives all historical data will be completely gone.
1659 /// Default value: 14 days
1661 /// [`historical_estimated_channel_liquidity_probabilities`]: ProbabilisticScorer::historical_estimated_channel_liquidity_probabilities
1663 pub extern "C" fn ProbabilisticScoringDecayParameters_set_historical_no_updates_half_life(this_ptr: &mut ProbabilisticScoringDecayParameters, mut val: u64) {
1664 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.historical_no_updates_half_life = core::time::Duration::from_secs(val);
1666 /// Whenever this amount of time elapses since the last update to a channel's liquidity bounds,
1667 /// the distance from the bounds to \"zero\" is cut in half. In other words, the lower-bound on
1668 /// the available liquidity is halved and the upper-bound moves half-way to the channel's total
1671 /// Because halving the liquidity bounds grows the uncertainty on the channel's liquidity,
1672 /// the penalty for an amount within the new bounds may change. See the [`ProbabilisticScorer`]
1673 /// struct documentation for more info on the way the liquidity bounds are used.
1675 /// For example, if the channel's capacity is 1 million sats, and the current upper and lower
1676 /// liquidity bounds are 200,000 sats and 600,000 sats, after this amount of time the upper
1677 /// and lower liquidity bounds will be decayed to 100,000 and 800,000 sats.
1679 /// Default value: 6 hours
1683 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
1684 /// liquidity knowledge will never decay except when the bounds cross.
1686 pub extern "C" fn ProbabilisticScoringDecayParameters_get_liquidity_offset_half_life(this_ptr: &ProbabilisticScoringDecayParameters) -> u64 {
1687 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_offset_half_life;
1690 /// Whenever this amount of time elapses since the last update to a channel's liquidity bounds,
1691 /// the distance from the bounds to \"zero\" is cut in half. In other words, the lower-bound on
1692 /// the available liquidity is halved and the upper-bound moves half-way to the channel's total
1695 /// Because halving the liquidity bounds grows the uncertainty on the channel's liquidity,
1696 /// the penalty for an amount within the new bounds may change. See the [`ProbabilisticScorer`]
1697 /// struct documentation for more info on the way the liquidity bounds are used.
1699 /// For example, if the channel's capacity is 1 million sats, and the current upper and lower
1700 /// liquidity bounds are 200,000 sats and 600,000 sats, after this amount of time the upper
1701 /// and lower liquidity bounds will be decayed to 100,000 and 800,000 sats.
1703 /// Default value: 6 hours
1707 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
1708 /// liquidity knowledge will never decay except when the bounds cross.
1710 pub extern "C" fn ProbabilisticScoringDecayParameters_set_liquidity_offset_half_life(this_ptr: &mut ProbabilisticScoringDecayParameters, mut val: u64) {
1711 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_offset_half_life = core::time::Duration::from_secs(val);
1713 /// Constructs a new ProbabilisticScoringDecayParameters given each field
1716 pub extern "C" fn ProbabilisticScoringDecayParameters_new(mut historical_no_updates_half_life_arg: u64, mut liquidity_offset_half_life_arg: u64) -> ProbabilisticScoringDecayParameters {
1717 ProbabilisticScoringDecayParameters { inner: ObjOps::heap_alloc(nativeProbabilisticScoringDecayParameters {
1718 historical_no_updates_half_life: core::time::Duration::from_secs(historical_no_updates_half_life_arg),
1719 liquidity_offset_half_life: core::time::Duration::from_secs(liquidity_offset_half_life_arg),
1720 }), is_owned: true }
1722 impl Clone for ProbabilisticScoringDecayParameters {
1723 fn clone(&self) -> Self {
1725 inner: if <*mut nativeProbabilisticScoringDecayParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
1726 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
1732 /// Used only if an object of this type is returned as a trait impl by a method
1733 pub(crate) extern "C" fn ProbabilisticScoringDecayParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
1734 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeProbabilisticScoringDecayParameters)).clone() })) as *mut c_void
1737 /// Creates a copy of the ProbabilisticScoringDecayParameters
1738 pub extern "C" fn ProbabilisticScoringDecayParameters_clone(orig: &ProbabilisticScoringDecayParameters) -> ProbabilisticScoringDecayParameters {
1741 /// Creates a "default" ProbabilisticScoringDecayParameters. See struct and individual field documentaiton for details on which values are used.
1744 pub extern "C" fn ProbabilisticScoringDecayParameters_default() -> ProbabilisticScoringDecayParameters {
1745 ProbabilisticScoringDecayParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
1747 /// Creates a new scorer using the given scoring parameters for sending payments from a node
1748 /// through a network graph.
1751 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 {
1752 let mut ret = lightning::routing::scoring::ProbabilisticScorer::new(*unsafe { Box::from_raw(decay_params.take_inner()) }, network_graph.get_native_ref(), logger);
1753 crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
1756 /// Dump the contents of this scorer into the configured logger.
1758 /// Note that this writes roughly one line per channel for which we have a liquidity estimate,
1759 /// which may be a substantial amount of log output.
1761 pub extern "C" fn ProbabilisticScorer_debug_log_liquidity_stats(this_arg: &crate::lightning::routing::scoring::ProbabilisticScorer) {
1762 unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.debug_log_liquidity_stats()
1765 /// Query the estimated minimum and maximum liquidity available for sending a payment over the
1766 /// channel with `scid` towards the given `target` node.
1769 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 {
1770 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.estimated_channel_liquidity_range(scid, target.get_native_ref());
1771 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 }) };
1775 /// Query the historical estimated minimum and maximum liquidity available for sending a
1776 /// payment over the channel with `scid` towards the given `target` node.
1778 /// Returns two sets of 32 buckets. The first set describes the lower-bound liquidity history,
1779 /// the second set describes the upper-bound liquidity history. Each bucket describes the
1780 /// relative frequency at which we've seen a liquidity bound in the bucket's range relative to
1781 /// the channel's total capacity, on an arbitrary scale. Because the values are slowly decayed,
1782 /// more recent data points are weighted more heavily than older datapoints.
1784 /// Note that the range of each bucket varies by its location to provide more granular results
1785 /// at the edges of a channel's capacity, where it is more likely to sit.
1787 /// When scoring, the estimated probability that an upper-/lower-bound lies in a given bucket
1788 /// is calculated by dividing that bucket's value with the total value of all buckets.
1790 /// For example, using a lower bucket count for illustrative purposes, a value of
1791 /// `[0, 0, 0, ..., 0, 32]` indicates that we believe the probability of a bound being very
1792 /// close to the channel's capacity to be 100%, and have never (recently) seen it in any other
1793 /// bucket. A value of `[31, 0, 0, ..., 0, 0, 32]` indicates we've seen the bound being both
1794 /// in the top and bottom bucket, and roughly with similar (recent) frequency.
1796 /// Because the datapoints are decayed slowly over time, values will eventually return to
1797 /// `Some(([0; 32], [0; 32]))` or `None` if no data remains for a channel.
1799 /// In order to fetch a single success probability from the buckets provided here, as used in
1800 /// the scoring model, see [`Self::historical_estimated_payment_success_probability`].
1803 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 {
1804 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.historical_estimated_channel_liquidity_probabilities(scid, target.get_native_ref());
1805 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 }) };
1809 /// Query the probability of payment success sending the given `amount_msat` over the channel
1810 /// with `scid` towards the given `target` node, based on the historical estimated liquidity
1813 /// These are the same bounds as returned by
1814 /// [`Self::historical_estimated_channel_liquidity_probabilities`] (but not those returned by
1815 /// [`Self::estimated_channel_liquidity_range`]).
1818 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 {
1819 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());
1820 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() }) };
1824 impl From<nativeProbabilisticScorer> for crate::lightning::routing::scoring::ScoreLookUp {
1825 fn from(obj: nativeProbabilisticScorer) -> Self {
1826 let rust_obj = crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
1827 let mut ret = ProbabilisticScorer_as_ScoreLookUp(&rust_obj);
1828 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
1829 core::mem::forget(rust_obj);
1830 ret.free = Some(ProbabilisticScorer_free_void);
1834 /// Constructs a new ScoreLookUp which calls the relevant methods on this_arg.
1835 /// This copies the `inner` pointer in this_arg and thus the returned ScoreLookUp must be freed before this_arg is
1837 pub extern "C" fn ProbabilisticScorer_as_ScoreLookUp(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::ScoreLookUp {
1838 crate::lightning::routing::scoring::ScoreLookUp {
1839 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1841 channel_penalty_msat: ProbabilisticScorer_ScoreLookUp_channel_penalty_msat,
1846 extern "C" fn ProbabilisticScorer_ScoreLookUp_channel_penalty_msat(this_arg: *const c_void, candidate: &crate::lightning::routing::router::CandidateRouteHop, mut usage: crate::lightning::routing::scoring::ChannelUsage, score_params: &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
1847 let mut ret = <nativeProbabilisticScorer as lightning::routing::scoring::ScoreLookUp>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &candidate.to_native(), *unsafe { Box::from_raw(usage.take_inner()) }, score_params.get_native_ref());
1851 impl From<nativeProbabilisticScorer> for crate::lightning::routing::scoring::ScoreUpdate {
1852 fn from(obj: nativeProbabilisticScorer) -> Self {
1853 let rust_obj = crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
1854 let mut ret = ProbabilisticScorer_as_ScoreUpdate(&rust_obj);
1855 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
1856 core::mem::forget(rust_obj);
1857 ret.free = Some(ProbabilisticScorer_free_void);
1861 /// Constructs a new ScoreUpdate which calls the relevant methods on this_arg.
1862 /// This copies the `inner` pointer in this_arg and thus the returned ScoreUpdate must be freed before this_arg is
1864 pub extern "C" fn ProbabilisticScorer_as_ScoreUpdate(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::ScoreUpdate {
1865 crate::lightning::routing::scoring::ScoreUpdate {
1866 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1868 payment_path_failed: ProbabilisticScorer_ScoreUpdate_payment_path_failed,
1869 payment_path_successful: ProbabilisticScorer_ScoreUpdate_payment_path_successful,
1870 probe_failed: ProbabilisticScorer_ScoreUpdate_probe_failed,
1871 probe_successful: ProbabilisticScorer_ScoreUpdate_probe_successful,
1872 time_passed: ProbabilisticScorer_ScoreUpdate_time_passed,
1876 extern "C" fn ProbabilisticScorer_ScoreUpdate_payment_path_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64, mut duration_since_epoch: u64) {
1877 <nativeProbabilisticScorer as lightning::routing::scoring::ScoreUpdate>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref(), short_channel_id, core::time::Duration::from_secs(duration_since_epoch))
1879 extern "C" fn ProbabilisticScorer_ScoreUpdate_payment_path_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut duration_since_epoch: u64) {
1880 <nativeProbabilisticScorer as lightning::routing::scoring::ScoreUpdate>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref(), core::time::Duration::from_secs(duration_since_epoch))
1882 extern "C" fn ProbabilisticScorer_ScoreUpdate_probe_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64, mut duration_since_epoch: u64) {
1883 <nativeProbabilisticScorer as lightning::routing::scoring::ScoreUpdate>::probe_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref(), short_channel_id, core::time::Duration::from_secs(duration_since_epoch))
1885 extern "C" fn ProbabilisticScorer_ScoreUpdate_probe_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut duration_since_epoch: u64) {
1886 <nativeProbabilisticScorer as lightning::routing::scoring::ScoreUpdate>::probe_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref(), core::time::Duration::from_secs(duration_since_epoch))
1888 extern "C" fn ProbabilisticScorer_ScoreUpdate_time_passed(this_arg: *mut c_void, mut duration_since_epoch: u64) {
1889 <nativeProbabilisticScorer as lightning::routing::scoring::ScoreUpdate>::time_passed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, core::time::Duration::from_secs(duration_since_epoch))
1892 impl From<nativeProbabilisticScorer> for crate::lightning::routing::scoring::Score {
1893 fn from(obj: nativeProbabilisticScorer) -> Self {
1894 let rust_obj = crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
1895 let mut ret = ProbabilisticScorer_as_Score(&rust_obj);
1896 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
1897 core::mem::forget(rust_obj);
1898 ret.free = Some(ProbabilisticScorer_free_void);
1902 /// Constructs a new Score which calls the relevant methods on this_arg.
1903 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
1905 pub extern "C" fn ProbabilisticScorer_as_Score(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::Score {
1906 crate::lightning::routing::scoring::Score {
1907 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1909 ScoreLookUp: crate::lightning::routing::scoring::ScoreLookUp {
1910 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1912 channel_penalty_msat: ProbabilisticScorer_ScoreLookUp_channel_penalty_msat,
1914 ScoreUpdate: crate::lightning::routing::scoring::ScoreUpdate {
1915 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1917 payment_path_failed: ProbabilisticScorer_ScoreUpdate_payment_path_failed,
1918 payment_path_successful: ProbabilisticScorer_ScoreUpdate_payment_path_successful,
1919 probe_failed: ProbabilisticScorer_ScoreUpdate_probe_failed,
1920 probe_successful: ProbabilisticScorer_ScoreUpdate_probe_successful,
1921 time_passed: ProbabilisticScorer_ScoreUpdate_time_passed,
1923 write: ProbabilisticScorer_write_void,
1930 use alloc::str::FromStr;
1931 use alloc::string::String;
1932 use core::ffi::c_void;
1933 use core::convert::Infallible;
1934 use bitcoin::hashes::Hash;
1935 use crate::c_types::*;
1936 #[cfg(feature="no-std")]
1937 use alloc::{vec::Vec, boxed::Box};
1940 mod bucketed_history {
1942 use alloc::str::FromStr;
1943 use alloc::string::String;
1944 use core::ffi::c_void;
1945 use core::convert::Infallible;
1946 use bitcoin::hashes::Hash;
1947 use crate::c_types::*;
1948 #[cfg(feature="no-std")]
1949 use alloc::{vec::Vec, boxed::Box};
1953 /// Serialize the ProbabilisticScorer object into a byte array which can be read by ProbabilisticScorer_read
1954 pub extern "C" fn ProbabilisticScorer_write(obj: &crate::lightning::routing::scoring::ProbabilisticScorer) -> crate::c_types::derived::CVec_u8Z {
1955 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
1958 pub(crate) extern "C" fn ProbabilisticScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
1959 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeProbabilisticScorer) })
1962 /// Read a ProbabilisticScorer from a byte array, created by ProbabilisticScorer_write
1963 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 {
1964 let arg_a_conv = *unsafe { Box::from_raw(arg_a.take_inner()) };
1965 let arg_b_conv = arg_b.get_native_ref();
1966 let arg_c_conv = arg_c;
1967 let arg_conv = (arg_a_conv, arg_b_conv, arg_c_conv);
1968 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);
1969 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() };