1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
4 // This file is licensed under the license available in the LICENSE or LICENSE.md
5 // file in the root of this repository or, if no such file exists, the same
6 // license as that which applies to the original source files from which this
7 // source was automatically generated.
9 //! Utilities for scoring payment channels.
11 //! [`ProbabilisticScorer`] may be given to [`find_route`] to score payment channels during path
12 //! finding when a custom [`Score`] implementation is not needed.
17 //! # extern crate bitcoin;
19 //! # use lightning::routing::gossip::NetworkGraph;
20 //! # use lightning::routing::router::{RouteParameters, find_route};
21 //! # use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
22 //! # use lightning::chain::keysinterface::{KeysManager, KeysInterface};
23 //! # use lightning::util::logger::{Logger, Record};
24 //! # use bitcoin::secp256k1::PublicKey;
26 //! # struct FakeLogger {};
27 //! # impl Logger for FakeLogger {
28 //! # fn log(&self, record: &Record) { unimplemented!() }
30 //! # fn find_scored_route(payer: PublicKey, route_params: RouteParameters, network_graph: NetworkGraph<&FakeLogger>) {
31 //! # let logger = FakeLogger {};
33 //! // Use the default channel penalties.
34 //! let params = ProbabilisticScoringParameters::default();
35 //! let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
37 //! // Or use custom channel penalties.
38 //! let params = ProbabilisticScoringParameters {
39 //! liquidity_penalty_multiplier_msat: 2 * 1000,
40 //! ..ProbabilisticScoringParameters::default()
42 //! let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
43 //! # let random_seed_bytes = [42u8; 32];
45 //! let route = find_route(&payer, &route_params, &network_graph, None, &logger, &scorer, &random_seed_bytes);
51 //! Persisting when built with feature `no-std` and restoring without it, or vice versa, uses
52 //! different types and thus is undefined.
54 //! [`find_route`]: crate::routing::router::find_route
56 use alloc::str::FromStr;
57 use core::ffi::c_void;
58 use core::convert::Infallible;
59 use bitcoin::hashes::Hash;
60 use crate::c_types::*;
61 #[cfg(feature="no-std")]
62 use alloc::{vec::Vec, boxed::Box};
64 /// An interface used to score payment channels for path finding.
66 ///\tScoring is in terms of fees willing to be paid in order to avoid routing through a channel.
69 /// An opaque pointer which is passed to your function implementations as an argument.
70 /// This has no meaning in the LDK, and can be NULL or any other value.
71 pub this_arg: *mut c_void,
72 /// Returns the fee in msats willing to be paid to avoid routing `send_amt_msat` through the
73 /// given channel in the direction from `source` to `target`.
75 /// The channel's capacity (less any other MPP parts that are also being considered for use in
76 /// the same payment) is given by `capacity_msat`. It may be determined from various sources
77 /// such as a chain data, network gossip, or invoice hints. For invoice hints, a capacity near
78 /// [`u64::max_value`] is given to indicate sufficient capacity for the invoice's full amount.
79 /// Thus, implementations should be overflow-safe.
81 pub channel_penalty_msat: extern "C" fn (this_arg: *const c_void, short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, usage: crate::lightning::routing::scoring::ChannelUsage) -> u64,
82 /// Handles updating channel penalties after failing to route through a channel.
83 pub payment_path_failed: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ, short_channel_id: u64),
84 /// Handles updating channel penalties after successfully routing along a path.
85 pub payment_path_successful: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ),
86 /// Handles updating channel penalties after a probe over the given path failed.
87 pub probe_failed: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ, short_channel_id: u64),
88 /// Handles updating channel penalties after a probe over the given path succeeded.
89 pub probe_successful: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ),
90 /// Serialize the object into a byte array
91 pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
92 /// Frees any resources associated with this object given its this_arg pointer.
93 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
94 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
96 unsafe impl Send for Score {}
97 unsafe impl Sync for Score {}
99 pub(crate) extern "C" fn Score_clone_fields(orig: &Score) -> Score {
101 this_arg: orig.this_arg,
102 channel_penalty_msat: Clone::clone(&orig.channel_penalty_msat),
103 payment_path_failed: Clone::clone(&orig.payment_path_failed),
104 payment_path_successful: Clone::clone(&orig.payment_path_successful),
105 probe_failed: Clone::clone(&orig.probe_failed),
106 probe_successful: Clone::clone(&orig.probe_successful),
107 write: Clone::clone(&orig.write),
108 free: Clone::clone(&orig.free),
111 impl lightning::util::ser::Writeable for Score {
112 fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
113 let vec = (self.write)(self.this_arg);
114 w.write_all(vec.as_slice())
118 use lightning::routing::scoring::Score as rustScore;
119 impl rustScore for Score {
120 fn channel_penalty_msat(&self, mut short_channel_id: u64, mut source: &lightning::routing::gossip::NodeId, mut target: &lightning::routing::gossip::NodeId, mut usage: lightning::routing::scoring::ChannelUsage) -> u64 {
121 let mut ret = (self.channel_penalty_msat)(self.this_arg, short_channel_id, &crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((source as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false }, &crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((target as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false }, crate::lightning::routing::scoring::ChannelUsage { inner: ObjOps::heap_alloc(usage), is_owned: true });
124 fn payment_path_failed(&mut self, mut path: &[&lightning::routing::router::RouteHop], mut short_channel_id: u64) {
125 let mut local_path = Vec::new(); for item in path.iter() { local_path.push( { crate::lightning::routing::router::RouteHop { inner: unsafe { ObjOps::nonnull_ptr_to_inner(((*item) as *const lightning::routing::router::RouteHop<>) as *mut _) }, is_owned: false } }); };
126 (self.payment_path_failed)(self.this_arg, local_path.into(), short_channel_id)
128 fn payment_path_successful(&mut self, mut path: &[&lightning::routing::router::RouteHop]) {
129 let mut local_path = Vec::new(); for item in path.iter() { local_path.push( { crate::lightning::routing::router::RouteHop { inner: unsafe { ObjOps::nonnull_ptr_to_inner(((*item) as *const lightning::routing::router::RouteHop<>) as *mut _) }, is_owned: false } }); };
130 (self.payment_path_successful)(self.this_arg, local_path.into())
132 fn probe_failed(&mut self, mut path: &[&lightning::routing::router::RouteHop], mut short_channel_id: u64) {
133 let mut local_path = Vec::new(); for item in path.iter() { local_path.push( { crate::lightning::routing::router::RouteHop { inner: unsafe { ObjOps::nonnull_ptr_to_inner(((*item) as *const lightning::routing::router::RouteHop<>) as *mut _) }, is_owned: false } }); };
134 (self.probe_failed)(self.this_arg, local_path.into(), short_channel_id)
136 fn probe_successful(&mut self, mut path: &[&lightning::routing::router::RouteHop]) {
137 let mut local_path = Vec::new(); for item in path.iter() { local_path.push( { crate::lightning::routing::router::RouteHop { inner: unsafe { ObjOps::nonnull_ptr_to_inner(((*item) as *const lightning::routing::router::RouteHop<>) as *mut _) }, is_owned: false } }); };
138 (self.probe_successful)(self.this_arg, local_path.into())
142 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
143 // directly as a Deref trait in higher-level structs:
144 impl core::ops::Deref for Score {
146 fn deref(&self) -> &Self {
150 /// Calls the free function if one is set
152 pub extern "C" fn Score_free(this_ptr: Score) { }
153 impl Drop for Score {
155 if let Some(f) = self.free {
160 /// A scorer that is accessed under a lock.
162 /// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
163 /// having shared ownership of a scorer but without requiring internal locking in [`Score`]
164 /// implementations. Internal locking would be detrimental to route finding performance and could
165 /// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
167 /// [`find_route`]: crate::routing::router::find_route
169 pub struct LockableScore {
170 /// An opaque pointer which is passed to your function implementations as an argument.
171 /// This has no meaning in the LDK, and can be NULL or any other value.
172 pub this_arg: *mut c_void,
173 /// Returns the locked scorer.
175 pub lock: extern "C" fn (this_arg: *const c_void) -> crate::lightning::routing::scoring::Score,
176 /// Frees any resources associated with this object given its this_arg pointer.
177 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
178 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
180 unsafe impl Send for LockableScore {}
181 unsafe impl Sync for LockableScore {}
183 pub(crate) extern "C" fn LockableScore_clone_fields(orig: &LockableScore) -> LockableScore {
185 this_arg: orig.this_arg,
186 lock: Clone::clone(&orig.lock),
187 free: Clone::clone(&orig.free),
191 use lightning::routing::scoring::LockableScore as rustLockableScore;
192 impl<'a> rustLockableScore<'a> for LockableScore {
193 type Locked = crate::lightning::routing::scoring::Score;
194 fn lock(&'a self) -> crate::lightning::routing::scoring::Score {
195 let mut ret = (self.lock)(self.this_arg);
200 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
201 // directly as a Deref trait in higher-level structs:
202 impl core::ops::Deref for LockableScore {
204 fn deref(&self) -> &Self {
208 /// Calls the free function if one is set
210 pub extern "C" fn LockableScore_free(this_ptr: LockableScore) { }
211 impl Drop for LockableScore {
213 if let Some(f) = self.free {
218 /// Refers to a scorer that is accessible under lock and also writeable to disk
220 /// We need this trait to be able to pass in a scorer to `lightning-background-processor` that will enable us to
221 /// use the Persister to persist it.
223 pub struct WriteableScore {
224 /// An opaque pointer which is passed to your function implementations as an argument.
225 /// This has no meaning in the LDK, and can be NULL or any other value.
226 pub this_arg: *mut c_void,
227 /// Implementation of LockableScore for this object.
228 pub LockableScore: crate::lightning::routing::scoring::LockableScore,
229 /// Serialize the object into a byte array
230 pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
231 /// Frees any resources associated with this object given its this_arg pointer.
232 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
233 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
235 unsafe impl Send for WriteableScore {}
236 unsafe impl Sync for WriteableScore {}
238 pub(crate) extern "C" fn WriteableScore_clone_fields(orig: &WriteableScore) -> WriteableScore {
240 this_arg: orig.this_arg,
241 LockableScore: crate::lightning::routing::scoring::LockableScore_clone_fields(&orig.LockableScore),
242 write: Clone::clone(&orig.write),
243 free: Clone::clone(&orig.free),
246 impl<'a> lightning::routing::scoring::LockableScore<'a> for WriteableScore {
247 type Locked = crate::lightning::routing::scoring::Score;
248 fn lock(&'a self) -> crate::lightning::routing::scoring::Score {
249 let mut ret = (self.LockableScore.lock)(self.LockableScore.this_arg);
253 impl lightning::util::ser::Writeable for WriteableScore {
254 fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
255 let vec = (self.write)(self.this_arg);
256 w.write_all(vec.as_slice())
260 use lightning::routing::scoring::WriteableScore as rustWriteableScore;
261 impl<'a> rustWriteableScore<'a> for WriteableScore {
264 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
265 // directly as a Deref trait in higher-level structs:
266 impl core::ops::Deref for WriteableScore {
268 fn deref(&self) -> &Self {
272 /// Calls the free function if one is set
274 pub extern "C" fn WriteableScore_free(this_ptr: WriteableScore) { }
275 impl Drop for WriteableScore {
277 if let Some(f) = self.free {
283 use lightning::routing::scoring::MultiThreadedLockableScore as nativeMultiThreadedLockableScoreImport;
284 pub(crate) type nativeMultiThreadedLockableScore = nativeMultiThreadedLockableScoreImport<crate::lightning::routing::scoring::Score>;
286 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
289 pub struct MultiThreadedLockableScore {
290 /// A pointer to the opaque Rust object.
292 /// Nearly everywhere, inner must be non-null, however in places where
293 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
294 pub inner: *mut nativeMultiThreadedLockableScore,
295 /// Indicates that this is the only struct which contains the same pointer.
297 /// Rust functions which take ownership of an object provided via an argument require
298 /// this to be true and invalidate the object pointed to by inner.
302 impl Drop for MultiThreadedLockableScore {
304 if self.is_owned && !<*mut nativeMultiThreadedLockableScore>::is_null(self.inner) {
305 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
309 /// Frees any resources used by the MultiThreadedLockableScore, if is_owned is set and inner is non-NULL.
311 pub extern "C" fn MultiThreadedLockableScore_free(this_obj: MultiThreadedLockableScore) { }
313 /// Used only if an object of this type is returned as a trait impl by a method
314 pub(crate) extern "C" fn MultiThreadedLockableScore_free_void(this_ptr: *mut c_void) {
315 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMultiThreadedLockableScore); }
318 impl MultiThreadedLockableScore {
319 pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedLockableScore {
320 unsafe { &*ObjOps::untweak_ptr(self.inner) }
322 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedLockableScore {
323 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
325 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
326 pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedLockableScore {
327 assert!(self.is_owned);
328 let ret = ObjOps::untweak_ptr(self.inner);
329 self.inner = core::ptr::null_mut();
334 use lightning::routing::scoring::MultiThreadedScoreLock as nativeMultiThreadedScoreLockImport;
335 pub(crate) type nativeMultiThreadedScoreLock = nativeMultiThreadedScoreLockImport<'static, crate::lightning::routing::scoring::Score>;
337 /// A locked `MultiThreadedLockableScore`.
340 pub struct MultiThreadedScoreLock {
341 /// A pointer to the opaque Rust object.
343 /// Nearly everywhere, inner must be non-null, however in places where
344 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
345 pub inner: *mut nativeMultiThreadedScoreLock,
346 /// Indicates that this is the only struct which contains the same pointer.
348 /// Rust functions which take ownership of an object provided via an argument require
349 /// this to be true and invalidate the object pointed to by inner.
353 impl Drop for MultiThreadedScoreLock {
355 if self.is_owned && !<*mut nativeMultiThreadedScoreLock>::is_null(self.inner) {
356 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
360 /// Frees any resources used by the MultiThreadedScoreLock, if is_owned is set and inner is non-NULL.
362 pub extern "C" fn MultiThreadedScoreLock_free(this_obj: MultiThreadedScoreLock) { }
364 /// Used only if an object of this type is returned as a trait impl by a method
365 pub(crate) extern "C" fn MultiThreadedScoreLock_free_void(this_ptr: *mut c_void) {
366 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMultiThreadedScoreLock); }
369 impl MultiThreadedScoreLock {
370 pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedScoreLock {
371 unsafe { &*ObjOps::untweak_ptr(self.inner) }
373 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedScoreLock {
374 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
376 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
377 pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedScoreLock {
378 assert!(self.is_owned);
379 let ret = ObjOps::untweak_ptr(self.inner);
380 self.inner = core::ptr::null_mut();
384 impl From<nativeMultiThreadedScoreLock> for crate::lightning::routing::scoring::Score {
385 fn from(obj: nativeMultiThreadedScoreLock) -> Self {
386 let mut rust_obj = MultiThreadedScoreLock { inner: ObjOps::heap_alloc(obj), is_owned: true };
387 let mut ret = MultiThreadedScoreLock_as_Score(&rust_obj);
388 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
389 rust_obj.inner = core::ptr::null_mut();
390 ret.free = Some(MultiThreadedScoreLock_free_void);
394 /// Constructs a new Score which calls the relevant methods on this_arg.
395 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
397 pub extern "C" fn MultiThreadedScoreLock_as_Score(this_arg: &MultiThreadedScoreLock) -> crate::lightning::routing::scoring::Score {
398 crate::lightning::routing::scoring::Score {
399 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
401 channel_penalty_msat: MultiThreadedScoreLock_Score_channel_penalty_msat,
402 payment_path_failed: MultiThreadedScoreLock_Score_payment_path_failed,
403 payment_path_successful: MultiThreadedScoreLock_Score_payment_path_successful,
404 probe_failed: MultiThreadedScoreLock_Score_probe_failed,
405 probe_successful: MultiThreadedScoreLock_Score_probe_successful,
406 write: MultiThreadedScoreLock_write_void,
411 extern "C" fn MultiThreadedScoreLock_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, mut usage: crate::lightning::routing::scoring::ChannelUsage) -> u64 {
412 let mut ret = <nativeMultiThreadedScoreLock as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLock) }, short_channel_id, source.get_native_ref(), target.get_native_ref(), *unsafe { Box::from_raw(usage.take_inner()) });
415 extern "C" fn MultiThreadedScoreLock_Score_payment_path_failed(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ, mut short_channel_id: u64) {
416 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
417 <nativeMultiThreadedScoreLock as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLock) }, &local_path[..], short_channel_id)
419 extern "C" fn MultiThreadedScoreLock_Score_payment_path_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
420 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
421 <nativeMultiThreadedScoreLock as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLock) }, &local_path[..])
423 extern "C" fn MultiThreadedScoreLock_Score_probe_failed(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ, mut short_channel_id: u64) {
424 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
425 <nativeMultiThreadedScoreLock as lightning::routing::scoring::Score<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLock) }, &local_path[..], short_channel_id)
427 extern "C" fn MultiThreadedScoreLock_Score_probe_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
428 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
429 <nativeMultiThreadedScoreLock as lightning::routing::scoring::Score<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLock) }, &local_path[..])
433 /// Serialize the MultiThreadedScoreLock object into a byte array which can be read by MultiThreadedScoreLock_read
434 pub extern "C" fn MultiThreadedScoreLock_write(obj: &crate::lightning::routing::scoring::MultiThreadedScoreLock) -> crate::c_types::derived::CVec_u8Z {
435 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
438 pub(crate) extern "C" fn MultiThreadedScoreLock_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
439 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeMultiThreadedScoreLock) })
441 impl From<nativeMultiThreadedLockableScore> for crate::lightning::routing::scoring::LockableScore {
442 fn from(obj: nativeMultiThreadedLockableScore) -> Self {
443 let mut rust_obj = MultiThreadedLockableScore { inner: ObjOps::heap_alloc(obj), is_owned: true };
444 let mut ret = MultiThreadedLockableScore_as_LockableScore(&rust_obj);
445 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
446 rust_obj.inner = core::ptr::null_mut();
447 ret.free = Some(MultiThreadedLockableScore_free_void);
451 /// Constructs a new LockableScore which calls the relevant methods on this_arg.
452 /// This copies the `inner` pointer in this_arg and thus the returned LockableScore must be freed before this_arg is
454 pub extern "C" fn MultiThreadedLockableScore_as_LockableScore(this_arg: &MultiThreadedLockableScore) -> crate::lightning::routing::scoring::LockableScore {
455 crate::lightning::routing::scoring::LockableScore {
456 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
458 lock: MultiThreadedLockableScore_LockableScore_lock,
463 extern "C" fn MultiThreadedLockableScore_LockableScore_lock(this_arg: *const c_void) -> crate::lightning::routing::scoring::Score {
464 let mut ret = <nativeMultiThreadedLockableScore as lightning::routing::scoring::LockableScore<>>::lock(unsafe { &mut *(this_arg as *mut nativeMultiThreadedLockableScore) }, );
468 /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
471 pub extern "C" fn MultiThreadedLockableScore_new(mut score: crate::lightning::routing::scoring::Score) -> crate::lightning::routing::scoring::MultiThreadedLockableScore {
472 let mut ret = lightning::routing::scoring::MultiThreadedLockableScore::new(score);
473 crate::lightning::routing::scoring::MultiThreadedLockableScore { inner: ObjOps::heap_alloc(ret), is_owned: true }
477 use lightning::routing::scoring::ChannelUsage as nativeChannelUsageImport;
478 pub(crate) type nativeChannelUsage = nativeChannelUsageImport;
480 /// Proposed use of a channel passed as a parameter to [`Score::channel_penalty_msat`].
483 pub struct ChannelUsage {
484 /// A pointer to the opaque Rust object.
486 /// Nearly everywhere, inner must be non-null, however in places where
487 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
488 pub inner: *mut nativeChannelUsage,
489 /// Indicates that this is the only struct which contains the same pointer.
491 /// Rust functions which take ownership of an object provided via an argument require
492 /// this to be true and invalidate the object pointed to by inner.
496 impl Drop for ChannelUsage {
498 if self.is_owned && !<*mut nativeChannelUsage>::is_null(self.inner) {
499 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
503 /// Frees any resources used by the ChannelUsage, if is_owned is set and inner is non-NULL.
505 pub extern "C" fn ChannelUsage_free(this_obj: ChannelUsage) { }
507 /// Used only if an object of this type is returned as a trait impl by a method
508 pub(crate) extern "C" fn ChannelUsage_free_void(this_ptr: *mut c_void) {
509 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelUsage); }
513 pub(crate) fn get_native_ref(&self) -> &'static nativeChannelUsage {
514 unsafe { &*ObjOps::untweak_ptr(self.inner) }
516 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelUsage {
517 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
519 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
520 pub(crate) fn take_inner(mut self) -> *mut nativeChannelUsage {
521 assert!(self.is_owned);
522 let ret = ObjOps::untweak_ptr(self.inner);
523 self.inner = core::ptr::null_mut();
527 /// The amount to send through the channel, denominated in millisatoshis.
529 pub extern "C" fn ChannelUsage_get_amount_msat(this_ptr: &ChannelUsage) -> u64 {
530 let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_msat;
533 /// The amount to send through the channel, denominated in millisatoshis.
535 pub extern "C" fn ChannelUsage_set_amount_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
536 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_msat = val;
538 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
539 /// as part of a multi-path payment.
541 pub extern "C" fn ChannelUsage_get_inflight_htlc_msat(this_ptr: &ChannelUsage) -> u64 {
542 let mut inner_val = &mut this_ptr.get_native_mut_ref().inflight_htlc_msat;
545 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
546 /// as part of a multi-path payment.
548 pub extern "C" fn ChannelUsage_set_inflight_htlc_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
549 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inflight_htlc_msat = val;
551 /// The effective capacity of the channel.
553 pub extern "C" fn ChannelUsage_get_effective_capacity(this_ptr: &ChannelUsage) -> crate::lightning::routing::gossip::EffectiveCapacity {
554 let mut inner_val = &mut this_ptr.get_native_mut_ref().effective_capacity;
555 crate::lightning::routing::gossip::EffectiveCapacity::from_native(inner_val)
557 /// The effective capacity of the channel.
559 pub extern "C" fn ChannelUsage_set_effective_capacity(this_ptr: &mut ChannelUsage, mut val: crate::lightning::routing::gossip::EffectiveCapacity) {
560 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.effective_capacity = val.into_native();
562 /// Constructs a new ChannelUsage given each field
565 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 {
566 ChannelUsage { inner: ObjOps::heap_alloc(nativeChannelUsage {
567 amount_msat: amount_msat_arg,
568 inflight_htlc_msat: inflight_htlc_msat_arg,
569 effective_capacity: effective_capacity_arg.into_native(),
572 impl Clone for ChannelUsage {
573 fn clone(&self) -> Self {
575 inner: if <*mut nativeChannelUsage>::is_null(self.inner) { core::ptr::null_mut() } else {
576 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
582 /// Used only if an object of this type is returned as a trait impl by a method
583 pub(crate) extern "C" fn ChannelUsage_clone_void(this_ptr: *const c_void) -> *mut c_void {
584 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelUsage)).clone() })) as *mut c_void
587 /// Creates a copy of the ChannelUsage
588 pub extern "C" fn ChannelUsage_clone(orig: &ChannelUsage) -> ChannelUsage {
592 use lightning::routing::scoring::FixedPenaltyScorer as nativeFixedPenaltyScorerImport;
593 pub(crate) type nativeFixedPenaltyScorer = nativeFixedPenaltyScorerImport;
595 /// [`Score`] implementation that uses a fixed penalty.
598 pub struct FixedPenaltyScorer {
599 /// A pointer to the opaque Rust object.
601 /// Nearly everywhere, inner must be non-null, however in places where
602 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
603 pub inner: *mut nativeFixedPenaltyScorer,
604 /// Indicates that this is the only struct which contains the same pointer.
606 /// Rust functions which take ownership of an object provided via an argument require
607 /// this to be true and invalidate the object pointed to by inner.
611 impl Drop for FixedPenaltyScorer {
613 if self.is_owned && !<*mut nativeFixedPenaltyScorer>::is_null(self.inner) {
614 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
618 /// Frees any resources used by the FixedPenaltyScorer, if is_owned is set and inner is non-NULL.
620 pub extern "C" fn FixedPenaltyScorer_free(this_obj: FixedPenaltyScorer) { }
622 /// Used only if an object of this type is returned as a trait impl by a method
623 pub(crate) extern "C" fn FixedPenaltyScorer_free_void(this_ptr: *mut c_void) {
624 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeFixedPenaltyScorer); }
627 impl FixedPenaltyScorer {
628 pub(crate) fn get_native_ref(&self) -> &'static nativeFixedPenaltyScorer {
629 unsafe { &*ObjOps::untweak_ptr(self.inner) }
631 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFixedPenaltyScorer {
632 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
634 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
635 pub(crate) fn take_inner(mut self) -> *mut nativeFixedPenaltyScorer {
636 assert!(self.is_owned);
637 let ret = ObjOps::untweak_ptr(self.inner);
638 self.inner = core::ptr::null_mut();
642 impl Clone for FixedPenaltyScorer {
643 fn clone(&self) -> Self {
645 inner: if <*mut nativeFixedPenaltyScorer>::is_null(self.inner) { core::ptr::null_mut() } else {
646 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
652 /// Used only if an object of this type is returned as a trait impl by a method
653 pub(crate) extern "C" fn FixedPenaltyScorer_clone_void(this_ptr: *const c_void) -> *mut c_void {
654 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFixedPenaltyScorer)).clone() })) as *mut c_void
657 /// Creates a copy of the FixedPenaltyScorer
658 pub extern "C" fn FixedPenaltyScorer_clone(orig: &FixedPenaltyScorer) -> FixedPenaltyScorer {
661 /// Creates a new scorer using `penalty_msat`.
664 pub extern "C" fn FixedPenaltyScorer_with_penalty(mut penalty_msat: u64) -> crate::lightning::routing::scoring::FixedPenaltyScorer {
665 let mut ret = lightning::routing::scoring::FixedPenaltyScorer::with_penalty(penalty_msat);
666 crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
669 impl From<nativeFixedPenaltyScorer> for crate::lightning::routing::scoring::Score {
670 fn from(obj: nativeFixedPenaltyScorer) -> Self {
671 let mut rust_obj = FixedPenaltyScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
672 let mut ret = FixedPenaltyScorer_as_Score(&rust_obj);
673 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
674 rust_obj.inner = core::ptr::null_mut();
675 ret.free = Some(FixedPenaltyScorer_free_void);
679 /// Constructs a new Score which calls the relevant methods on this_arg.
680 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
682 pub extern "C" fn FixedPenaltyScorer_as_Score(this_arg: &FixedPenaltyScorer) -> crate::lightning::routing::scoring::Score {
683 crate::lightning::routing::scoring::Score {
684 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
686 channel_penalty_msat: FixedPenaltyScorer_Score_channel_penalty_msat,
687 payment_path_failed: FixedPenaltyScorer_Score_payment_path_failed,
688 payment_path_successful: FixedPenaltyScorer_Score_payment_path_successful,
689 probe_failed: FixedPenaltyScorer_Score_probe_failed,
690 probe_successful: FixedPenaltyScorer_Score_probe_successful,
691 write: FixedPenaltyScorer_write_void,
696 extern "C" fn FixedPenaltyScorer_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, mut usage: crate::lightning::routing::scoring::ChannelUsage) -> u64 {
697 let mut ret = <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, short_channel_id, source.get_native_ref(), target.get_native_ref(), *unsafe { Box::from_raw(usage.take_inner()) });
700 extern "C" fn FixedPenaltyScorer_Score_payment_path_failed(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ, mut short_channel_id: u64) {
701 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
702 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local_path[..], short_channel_id)
704 extern "C" fn FixedPenaltyScorer_Score_payment_path_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
705 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
706 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local_path[..])
708 extern "C" fn FixedPenaltyScorer_Score_probe_failed(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ, mut short_channel_id: u64) {
709 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
710 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local_path[..], short_channel_id)
712 extern "C" fn FixedPenaltyScorer_Score_probe_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
713 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
714 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local_path[..])
718 /// Serialize the FixedPenaltyScorer object into a byte array which can be read by FixedPenaltyScorer_read
719 pub extern "C" fn FixedPenaltyScorer_write(obj: &crate::lightning::routing::scoring::FixedPenaltyScorer) -> crate::c_types::derived::CVec_u8Z {
720 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
723 pub(crate) extern "C" fn FixedPenaltyScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
724 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFixedPenaltyScorer) })
727 /// Read a FixedPenaltyScorer from a byte array, created by FixedPenaltyScorer_write
728 pub extern "C" fn FixedPenaltyScorer_read(ser: crate::c_types::u8slice, arg: u64) -> crate::c_types::derived::CResult_FixedPenaltyScorerDecodeErrorZ {
730 let res: Result<lightning::routing::scoring::FixedPenaltyScorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
731 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
735 use lightning::routing::scoring::ProbabilisticScorer as nativeProbabilisticScorerImport;
736 pub(crate) type nativeProbabilisticScorer = nativeProbabilisticScorerImport<&'static lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger>;
738 /// [`Score`] implementation using channel success probability distributions.
740 /// Based on *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
741 /// and Stefan Richter [[1]]. Given the uncertainty of channel liquidity balances, probability
742 /// distributions are defined based on knowledge learned from successful and unsuccessful attempts.
743 /// Then the negative `log10` of the success probability is used to determine the cost of routing a
744 /// specific HTLC amount through a channel.
746 /// Knowledge about channel liquidity balances takes the form of upper and lower bounds on the
747 /// possible liquidity. Certainty of the bounds is decreased over time using a decay function. See
748 /// [`ProbabilisticScoringParameters`] for details.
750 /// Since the scorer aims to learn the current channel liquidity balances, it works best for nodes
751 /// with high payment volume or that actively probe the [`NetworkGraph`]. Nodes with low payment
752 /// volume are more likely to experience failed payment paths, which would need to be retried.
756 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
759 /// [1]: https://arxiv.org/abs/2107.05322
762 pub struct ProbabilisticScorer {
763 /// A pointer to the opaque Rust object.
765 /// Nearly everywhere, inner must be non-null, however in places where
766 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
767 pub inner: *mut nativeProbabilisticScorer,
768 /// Indicates that this is the only struct which contains the same pointer.
770 /// Rust functions which take ownership of an object provided via an argument require
771 /// this to be true and invalidate the object pointed to by inner.
775 impl Drop for ProbabilisticScorer {
777 if self.is_owned && !<*mut nativeProbabilisticScorer>::is_null(self.inner) {
778 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
782 /// Frees any resources used by the ProbabilisticScorer, if is_owned is set and inner is non-NULL.
784 pub extern "C" fn ProbabilisticScorer_free(this_obj: ProbabilisticScorer) { }
786 /// Used only if an object of this type is returned as a trait impl by a method
787 pub(crate) extern "C" fn ProbabilisticScorer_free_void(this_ptr: *mut c_void) {
788 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScorer); }
791 impl ProbabilisticScorer {
792 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScorer {
793 unsafe { &*ObjOps::untweak_ptr(self.inner) }
795 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScorer {
796 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
798 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
799 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScorer {
800 assert!(self.is_owned);
801 let ret = ObjOps::untweak_ptr(self.inner);
802 self.inner = core::ptr::null_mut();
807 use lightning::routing::scoring::ProbabilisticScoringParameters as nativeProbabilisticScoringParametersImport;
808 pub(crate) type nativeProbabilisticScoringParameters = nativeProbabilisticScoringParametersImport;
810 /// Parameters for configuring [`ProbabilisticScorer`].
812 /// Used to configure base, liquidity, and amount penalties, the sum of which comprises the channel
813 /// penalty (i.e., the amount in msats willing to be paid to avoid routing through the channel).
815 /// The penalty applied to any channel by the [`ProbabilisticScorer`] is the sum of each of the
819 pub struct ProbabilisticScoringParameters {
820 /// A pointer to the opaque Rust object.
822 /// Nearly everywhere, inner must be non-null, however in places where
823 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
824 pub inner: *mut nativeProbabilisticScoringParameters,
825 /// Indicates that this is the only struct which contains the same pointer.
827 /// Rust functions which take ownership of an object provided via an argument require
828 /// this to be true and invalidate the object pointed to by inner.
832 impl Drop for ProbabilisticScoringParameters {
834 if self.is_owned && !<*mut nativeProbabilisticScoringParameters>::is_null(self.inner) {
835 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
839 /// Frees any resources used by the ProbabilisticScoringParameters, if is_owned is set and inner is non-NULL.
841 pub extern "C" fn ProbabilisticScoringParameters_free(this_obj: ProbabilisticScoringParameters) { }
843 /// Used only if an object of this type is returned as a trait impl by a method
844 pub(crate) extern "C" fn ProbabilisticScoringParameters_free_void(this_ptr: *mut c_void) {
845 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScoringParameters); }
848 impl ProbabilisticScoringParameters {
849 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringParameters {
850 unsafe { &*ObjOps::untweak_ptr(self.inner) }
852 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringParameters {
853 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
855 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
856 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringParameters {
857 assert!(self.is_owned);
858 let ret = ObjOps::untweak_ptr(self.inner);
859 self.inner = core::ptr::null_mut();
863 /// A fixed penalty in msats to apply to each channel.
865 /// Default value: 500 msat
867 pub extern "C" fn ProbabilisticScoringParameters_get_base_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
868 let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
871 /// A fixed penalty in msats to apply to each channel.
873 /// Default value: 500 msat
875 pub extern "C" fn ProbabilisticScoringParameters_set_base_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
876 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
878 /// A multiplier used with the payment amount to calculate a fixed penalty applied to each
879 /// channel, in excess of the [`base_penalty_msat`].
881 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
882 /// fees plus penalty) for large payments. The penalty is computed as the product of this
883 /// multiplier and `2^30`ths of the payment amount.
885 /// ie `base_penalty_amount_multiplier_msat * amount_msat / 2^30`
887 /// Default value: 8,192 msat
889 /// [`base_penalty_msat`]: Self::base_penalty_msat
891 pub extern "C" fn ProbabilisticScoringParameters_get_base_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
892 let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_amount_multiplier_msat;
895 /// A multiplier used with the payment amount to calculate a fixed penalty applied to each
896 /// channel, in excess of the [`base_penalty_msat`].
898 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
899 /// fees plus penalty) for large payments. The penalty is computed as the product of this
900 /// multiplier and `2^30`ths of the payment amount.
902 /// ie `base_penalty_amount_multiplier_msat * amount_msat / 2^30`
904 /// Default value: 8,192 msat
906 /// [`base_penalty_msat`]: Self::base_penalty_msat
908 pub extern "C" fn ProbabilisticScoringParameters_set_base_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
909 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_amount_multiplier_msat = val;
911 /// A multiplier used in conjunction with the negative `log10` of the channel's success
912 /// probability for a payment to determine the liquidity penalty.
914 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
915 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
916 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
917 /// lower bounding the success probability to `0.01`) when the amount falls within the
918 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
919 /// result in a `u64::max_value` penalty, however.
921 /// Default value: 40,000 msat
923 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
925 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
926 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_multiplier_msat;
929 /// A multiplier used in conjunction with the negative `log10` of the channel's success
930 /// probability for a payment to determine the liquidity penalty.
932 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
933 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
934 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
935 /// lower bounding the success probability to `0.01`) when the amount falls within the
936 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
937 /// result in a `u64::max_value` penalty, however.
939 /// Default value: 40,000 msat
941 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
943 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
944 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_multiplier_msat = val;
946 /// The time required to elapse before any knowledge learned about channel liquidity balances is
949 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
950 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
951 /// the certainty of the channel liquidity balance.
953 /// Default value: 1 hour
957 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
958 /// liquidity knowledge will never decay except when the bounds cross.
960 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_offset_half_life(this_ptr: &ProbabilisticScoringParameters) -> u64 {
961 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_offset_half_life;
964 /// The time required to elapse before any knowledge learned about channel liquidity balances is
967 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
968 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
969 /// the certainty of the channel liquidity balance.
971 /// Default value: 1 hour
975 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
976 /// liquidity knowledge will never decay except when the bounds cross.
978 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_offset_half_life(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
979 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_offset_half_life = core::time::Duration::from_secs(val);
981 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
982 /// channel's success probability for the payment to determine the amount penalty.
984 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
985 /// fees plus penalty) for large payments. The penalty is computed as the product of this
986 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
987 /// success probability.
989 /// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
991 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
992 /// the amount will result in a penalty of the multiplier. And, as the success probability
993 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
994 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
997 /// Default value: 256 msat
999 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
1000 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_amount_multiplier_msat;
1003 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
1004 /// channel's success probability for the payment to determine the amount penalty.
1006 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
1007 /// fees plus penalty) for large payments. The penalty is computed as the product of this
1008 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
1009 /// success probability.
1011 /// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
1013 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
1014 /// the amount will result in a penalty of the multiplier. And, as the success probability
1015 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
1016 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
1019 /// Default value: 256 msat
1021 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
1022 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_amount_multiplier_msat = val;
1024 /// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
1025 /// channel's capacity, which makes us prefer nodes with a smaller `htlc_maximum_msat`. We
1026 /// treat such nodes preferentially as this makes balance discovery attacks harder to execute,
1027 /// thereby creating an incentive to restrict `htlc_maximum_msat` and improve privacy.
1029 /// Default value: 250 msat
1031 pub extern "C" fn ProbabilisticScoringParameters_get_anti_probing_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
1032 let mut inner_val = &mut this_ptr.get_native_mut_ref().anti_probing_penalty_msat;
1035 /// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
1036 /// channel's capacity, which makes us prefer nodes with a smaller `htlc_maximum_msat`. We
1037 /// treat such nodes preferentially as this makes balance discovery attacks harder to execute,
1038 /// thereby creating an incentive to restrict `htlc_maximum_msat` and improve privacy.
1040 /// Default value: 250 msat
1042 pub extern "C" fn ProbabilisticScoringParameters_set_anti_probing_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
1043 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.anti_probing_penalty_msat = val;
1045 /// This penalty is applied when the amount we're attempting to send over a channel exceeds our
1046 /// current estimate of the channel's available liquidity.
1048 /// Note that in this case all other penalties, including the
1049 /// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
1050 /// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
1051 /// applicable, are still included in the overall penalty.
1053 /// If you wish to avoid creating paths with such channels entirely, setting this to a value of
1054 /// `u64::max_value()` will guarantee that.
1056 /// Default value: 1_0000_0000_000 msat (1 Bitcoin)
1058 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1059 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1060 /// [`base_penalty_msat`]: Self::base_penalty_msat
1061 /// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
1063 pub extern "C" fn ProbabilisticScoringParameters_get_considered_impossible_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
1064 let mut inner_val = &mut this_ptr.get_native_mut_ref().considered_impossible_penalty_msat;
1067 /// This penalty is applied when the amount we're attempting to send over a channel exceeds our
1068 /// current estimate of the channel's available liquidity.
1070 /// Note that in this case all other penalties, including the
1071 /// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
1072 /// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
1073 /// applicable, are still included in the overall penalty.
1075 /// If you wish to avoid creating paths with such channels entirely, setting this to a value of
1076 /// `u64::max_value()` will guarantee that.
1078 /// Default value: 1_0000_0000_000 msat (1 Bitcoin)
1080 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1081 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1082 /// [`base_penalty_msat`]: Self::base_penalty_msat
1083 /// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
1085 pub extern "C" fn ProbabilisticScoringParameters_set_considered_impossible_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
1086 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.considered_impossible_penalty_msat = val;
1088 impl Clone for ProbabilisticScoringParameters {
1089 fn clone(&self) -> Self {
1091 inner: if <*mut nativeProbabilisticScoringParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
1092 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
1098 /// Used only if an object of this type is returned as a trait impl by a method
1099 pub(crate) extern "C" fn ProbabilisticScoringParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
1100 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeProbabilisticScoringParameters)).clone() })) as *mut c_void
1103 /// Creates a copy of the ProbabilisticScoringParameters
1104 pub extern "C" fn ProbabilisticScoringParameters_clone(orig: &ProbabilisticScoringParameters) -> ProbabilisticScoringParameters {
1107 /// Creates a new scorer using the given scoring parameters for sending payments from a node
1108 /// through a network graph.
1111 pub extern "C" fn ProbabilisticScorer_new(mut params: crate::lightning::routing::scoring::ProbabilisticScoringParameters, network_graph: &crate::lightning::routing::gossip::NetworkGraph, mut logger: crate::lightning::util::logger::Logger) -> crate::lightning::routing::scoring::ProbabilisticScorer {
1112 let mut ret = lightning::routing::scoring::ProbabilisticScorer::new(*unsafe { Box::from_raw(params.take_inner()) }, network_graph.get_native_ref(), logger);
1113 crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
1116 /// Dump the contents of this scorer into the configured logger.
1118 /// Note that this writes roughly one line per channel for which we have a liquidity estimate,
1119 /// which may be a substantial amount of log output.
1121 pub extern "C" fn ProbabilisticScorer_debug_log_liquidity_stats(this_arg: &crate::lightning::routing::scoring::ProbabilisticScorer) {
1122 unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.debug_log_liquidity_stats()
1125 /// Query the estimated minimum and maximum liquidity available for sending a payment over the
1126 /// channel with `scid` towards the given `target` node.
1129 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 {
1130 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.estimated_channel_liquidity_range(scid, target.get_native_ref());
1131 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 }) };
1135 /// Marks the node with the given `node_id` as banned, i.e.,
1136 /// it will be avoided during path finding.
1138 pub extern "C" fn ProbabilisticScorer_add_banned(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer, node_id: &crate::lightning::routing::gossip::NodeId) {
1139 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.add_banned(node_id.get_native_ref())
1142 /// Removes the node with the given `node_id` from the list of nodes to avoid.
1144 pub extern "C" fn ProbabilisticScorer_remove_banned(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer, node_id: &crate::lightning::routing::gossip::NodeId) {
1145 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.remove_banned(node_id.get_native_ref())
1148 /// Sets a manual penalty for the given node.
1150 pub extern "C" fn ProbabilisticScorer_set_manual_penalty(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer, node_id: &crate::lightning::routing::gossip::NodeId, mut penalty: u64) {
1151 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.set_manual_penalty(node_id.get_native_ref(), penalty)
1154 /// Removes the node with the given `node_id` from the list of manual penalties.
1156 pub extern "C" fn ProbabilisticScorer_remove_manual_penalty(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer, node_id: &crate::lightning::routing::gossip::NodeId) {
1157 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.remove_manual_penalty(node_id.get_native_ref())
1160 /// Clears the list of manual penalties that are applied during path finding.
1162 pub extern "C" fn ProbabilisticScorer_clear_manual_penalties(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer) {
1163 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.clear_manual_penalties()
1166 /// Marks all nodes in the given list as banned, i.e.,
1167 /// they will be avoided during path finding.
1169 pub extern "C" fn ProbabilisticScoringParameters_add_banned_from_list(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringParameters, mut node_ids: crate::c_types::derived::CVec_NodeIdZ) {
1170 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()) } }); };
1171 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringParameters)) }.add_banned_from_list(local_node_ids)
1174 /// Creates a "default" ProbabilisticScoringParameters. See struct and individual field documentaiton for details on which values are used.
1177 pub extern "C" fn ProbabilisticScoringParameters_default() -> ProbabilisticScoringParameters {
1178 ProbabilisticScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
1180 impl From<nativeProbabilisticScorer> for crate::lightning::routing::scoring::Score {
1181 fn from(obj: nativeProbabilisticScorer) -> Self {
1182 let mut rust_obj = ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
1183 let mut ret = ProbabilisticScorer_as_Score(&rust_obj);
1184 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
1185 rust_obj.inner = core::ptr::null_mut();
1186 ret.free = Some(ProbabilisticScorer_free_void);
1190 /// Constructs a new Score which calls the relevant methods on this_arg.
1191 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
1193 pub extern "C" fn ProbabilisticScorer_as_Score(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::Score {
1194 crate::lightning::routing::scoring::Score {
1195 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1197 channel_penalty_msat: ProbabilisticScorer_Score_channel_penalty_msat,
1198 payment_path_failed: ProbabilisticScorer_Score_payment_path_failed,
1199 payment_path_successful: ProbabilisticScorer_Score_payment_path_successful,
1200 probe_failed: ProbabilisticScorer_Score_probe_failed,
1201 probe_successful: ProbabilisticScorer_Score_probe_successful,
1202 write: ProbabilisticScorer_write_void,
1207 extern "C" fn ProbabilisticScorer_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, mut usage: crate::lightning::routing::scoring::ChannelUsage) -> u64 {
1208 let mut ret = <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, short_channel_id, source.get_native_ref(), target.get_native_ref(), *unsafe { Box::from_raw(usage.take_inner()) });
1211 extern "C" fn ProbabilisticScorer_Score_payment_path_failed(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ, mut short_channel_id: u64) {
1212 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1213 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..], short_channel_id)
1215 extern "C" fn ProbabilisticScorer_Score_payment_path_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
1216 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1217 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..])
1219 extern "C" fn ProbabilisticScorer_Score_probe_failed(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ, mut short_channel_id: u64) {
1220 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1221 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..], short_channel_id)
1223 extern "C" fn ProbabilisticScorer_Score_probe_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
1224 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1225 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..])
1230 use alloc::str::FromStr;
1231 use core::ffi::c_void;
1232 use core::convert::Infallible;
1233 use bitcoin::hashes::Hash;
1234 use crate::c_types::*;
1235 #[cfg(feature="no-std")]
1236 use alloc::{vec::Vec, boxed::Box};
1240 /// Serialize the ProbabilisticScorer object into a byte array which can be read by ProbabilisticScorer_read
1241 pub extern "C" fn ProbabilisticScorer_write(obj: &crate::lightning::routing::scoring::ProbabilisticScorer) -> crate::c_types::derived::CVec_u8Z {
1242 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
1245 pub(crate) extern "C" fn ProbabilisticScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
1246 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeProbabilisticScorer) })
1249 /// Read a ProbabilisticScorer from a byte array, created by ProbabilisticScorer_write
1250 pub extern "C" fn ProbabilisticScorer_read(ser: crate::c_types::u8slice, arg_a: crate::lightning::routing::scoring::ProbabilisticScoringParameters, arg_b: &crate::lightning::routing::gossip::NetworkGraph, arg_c: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_ProbabilisticScorerDecodeErrorZ {
1251 let arg_a_conv = *unsafe { Box::from_raw(arg_a.take_inner()) };
1252 let arg_b_conv = arg_b.get_native_ref();
1253 let arg_c_conv = arg_c;
1254 let arg_conv = (arg_a_conv, arg_b_conv, arg_c_conv);
1255 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);
1256 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };