Update auto-generated bindings for LDK 0.0.115
[ldk-c-bindings] / lightning-c-bindings / src / lightning / routing / scoring.rs
1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
3 //
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.
8
9 //! Utilities for scoring payment channels.
10 //!
11 //! [`ProbabilisticScorer`] may be given to [`find_route`] to score payment channels during path
12 //! finding when a custom [`Score`] implementation is not needed.
13 //!
14 //! # Example
15 //!
16 //! ```
17 //! # extern crate bitcoin;
18 //! #
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;
23 //! # use lightning::util::logger::{Logger, Record};
24 //! # use bitcoin::secp256k1::PublicKey;
25 //! #
26 //! # struct FakeLogger {};
27 //! # impl Logger for FakeLogger {
28 //! #     fn log(&self, record: &Record) { unimplemented!() }
29 //! # }
30 //! # fn find_scored_route(payer: PublicKey, route_params: RouteParameters, network_graph: NetworkGraph<&FakeLogger>) {
31 //! # let logger = FakeLogger {};
32 //! #
33 //! // Use the default channel penalties.
34 //! let params = ProbabilisticScoringParameters::default();
35 //! let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
36 //!
37 //! // Or use custom channel penalties.
38 //! let params = ProbabilisticScoringParameters {
39 //!     liquidity_penalty_multiplier_msat: 2 * 1000,
40 //!     ..ProbabilisticScoringParameters::default()
41 //! };
42 //! let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
43 //! # let random_seed_bytes = [42u8; 32];
44 //!
45 //! let route = find_route(&payer, &route_params, &network_graph, None, &logger, &scorer, &random_seed_bytes);
46 //! # }
47 //! ```
48 //!
49 //! # Note
50 //!
51 //! Persisting when built with feature `no-std` and restoring without it, or vice versa, uses
52 //! different types and thus is undefined.
53 //!
54 //! [`find_route`]: crate::routing::router::find_route
55
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};
63
64 /// An interface used to score payment channels for path finding.
65 ///
66 ///\tScoring is in terms of fees willing to be paid in order to avoid routing through a channel.
67 #[repr(C)]
68 pub struct Score {
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`.
74         ///
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.
80         #[must_use]
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::lightning::routing::router::Path, 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::lightning::routing::router::Path),
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::lightning::routing::router::Path, 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::lightning::routing::router::Path),
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)>,
95 }
96 unsafe impl Send for Score {}
97 unsafe impl Sync for Score {}
98 #[no_mangle]
99 pub(crate) extern "C" fn Score_clone_fields(orig: &Score) -> Score {
100         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),
109         }
110 }
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())
115         }
116 }
117
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 });
122                 ret
123         }
124         fn payment_path_failed(&mut self, mut path: &lightning::routing::router::Path, mut short_channel_id: u64) {
125                 (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)
126         }
127         fn payment_path_successful(&mut self, mut path: &lightning::routing::router::Path) {
128                 (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 })
129         }
130         fn probe_failed(&mut self, mut path: &lightning::routing::router::Path, mut short_channel_id: u64) {
131                 (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)
132         }
133         fn probe_successful(&mut self, mut path: &lightning::routing::router::Path) {
134                 (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 })
135         }
136 }
137
138 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
139 // directly as a Deref trait in higher-level structs:
140 impl core::ops::Deref for Score {
141         type Target = Self;
142         fn deref(&self) -> &Self {
143                 self
144         }
145 }
146 /// Calls the free function if one is set
147 #[no_mangle]
148 pub extern "C" fn Score_free(this_ptr: Score) { }
149 impl Drop for Score {
150         fn drop(&mut self) {
151                 if let Some(f) = self.free {
152                         f(self.this_arg);
153                 }
154         }
155 }
156 /// A scorer that is accessed under a lock.
157 ///
158 /// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
159 /// having shared ownership of a scorer but without requiring internal locking in [`Score`]
160 /// implementations. Internal locking would be detrimental to route finding performance and could
161 /// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
162 ///
163 /// [`find_route`]: crate::routing::router::find_route
164 #[repr(C)]
165 pub struct LockableScore {
166         /// An opaque pointer which is passed to your function implementations as an argument.
167         /// This has no meaning in the LDK, and can be NULL or any other value.
168         pub this_arg: *mut c_void,
169         /// Returns the locked scorer.
170         #[must_use]
171         pub lock: extern "C" fn (this_arg: *const c_void) -> crate::lightning::routing::scoring::Score,
172         /// Frees any resources associated with this object given its this_arg pointer.
173         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
174         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
175 }
176 unsafe impl Send for LockableScore {}
177 unsafe impl Sync for LockableScore {}
178 #[no_mangle]
179 pub(crate) extern "C" fn LockableScore_clone_fields(orig: &LockableScore) -> LockableScore {
180         LockableScore {
181                 this_arg: orig.this_arg,
182                 lock: Clone::clone(&orig.lock),
183                 free: Clone::clone(&orig.free),
184         }
185 }
186
187 use lightning::routing::scoring::LockableScore as rustLockableScore;
188 impl<'a> rustLockableScore<'a> for LockableScore {
189         type Locked = crate::lightning::routing::scoring::Score;
190         fn lock(&'a self) -> crate::lightning::routing::scoring::Score {
191                 let mut ret = (self.lock)(self.this_arg);
192                 ret
193         }
194 }
195
196 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
197 // directly as a Deref trait in higher-level structs:
198 impl core::ops::Deref for LockableScore {
199         type Target = Self;
200         fn deref(&self) -> &Self {
201                 self
202         }
203 }
204 /// Calls the free function if one is set
205 #[no_mangle]
206 pub extern "C" fn LockableScore_free(this_ptr: LockableScore) { }
207 impl Drop for LockableScore {
208         fn drop(&mut self) {
209                 if let Some(f) = self.free {
210                         f(self.this_arg);
211                 }
212         }
213 }
214 /// Refers to a scorer that is accessible under lock and also writeable to disk
215 ///
216 /// We need this trait to be able to pass in a scorer to `lightning-background-processor` that will enable us to
217 /// use the Persister to persist it.
218 #[repr(C)]
219 pub struct WriteableScore {
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 LockableScore for this object.
224         pub LockableScore: crate::lightning::routing::scoring::LockableScore,
225         /// Serialize the object into a byte array
226         pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
227         /// Frees any resources associated with this object given its this_arg pointer.
228         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
229         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
230 }
231 unsafe impl Send for WriteableScore {}
232 unsafe impl Sync for WriteableScore {}
233 #[no_mangle]
234 pub(crate) extern "C" fn WriteableScore_clone_fields(orig: &WriteableScore) -> WriteableScore {
235         WriteableScore {
236                 this_arg: orig.this_arg,
237                 LockableScore: crate::lightning::routing::scoring::LockableScore_clone_fields(&orig.LockableScore),
238                 write: Clone::clone(&orig.write),
239                 free: Clone::clone(&orig.free),
240         }
241 }
242 impl<'a> lightning::routing::scoring::LockableScore<'a> for WriteableScore {
243         type Locked = crate::lightning::routing::scoring::Score;
244         fn lock(&'a self) -> crate::lightning::routing::scoring::Score {
245                 let mut ret = (self.LockableScore.lock)(self.LockableScore.this_arg);
246                 ret
247         }
248 }
249 impl lightning::util::ser::Writeable for WriteableScore {
250         fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
251                 let vec = (self.write)(self.this_arg);
252                 w.write_all(vec.as_slice())
253         }
254 }
255
256 use lightning::routing::scoring::WriteableScore as rustWriteableScore;
257 impl<'a> rustWriteableScore<'a> for WriteableScore {
258 }
259
260 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
261 // directly as a Deref trait in higher-level structs:
262 impl core::ops::Deref for WriteableScore {
263         type Target = Self;
264         fn deref(&self) -> &Self {
265                 self
266         }
267 }
268 /// Calls the free function if one is set
269 #[no_mangle]
270 pub extern "C" fn WriteableScore_free(this_ptr: WriteableScore) { }
271 impl Drop for WriteableScore {
272         fn drop(&mut self) {
273                 if let Some(f) = self.free {
274                         f(self.this_arg);
275                 }
276         }
277 }
278
279 use lightning::routing::scoring::MultiThreadedLockableScore as nativeMultiThreadedLockableScoreImport;
280 pub(crate) type nativeMultiThreadedLockableScore = nativeMultiThreadedLockableScoreImport<crate::lightning::routing::scoring::Score>;
281
282 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
283 #[must_use]
284 #[repr(C)]
285 pub struct MultiThreadedLockableScore {
286         /// A pointer to the opaque Rust object.
287
288         /// Nearly everywhere, inner must be non-null, however in places where
289         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
290         pub inner: *mut nativeMultiThreadedLockableScore,
291         /// Indicates that this is the only struct which contains the same pointer.
292
293         /// Rust functions which take ownership of an object provided via an argument require
294         /// this to be true and invalidate the object pointed to by inner.
295         pub is_owned: bool,
296 }
297
298 impl Drop for MultiThreadedLockableScore {
299         fn drop(&mut self) {
300                 if self.is_owned && !<*mut nativeMultiThreadedLockableScore>::is_null(self.inner) {
301                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
302                 }
303         }
304 }
305 /// Frees any resources used by the MultiThreadedLockableScore, if is_owned is set and inner is non-NULL.
306 #[no_mangle]
307 pub extern "C" fn MultiThreadedLockableScore_free(this_obj: MultiThreadedLockableScore) { }
308 #[allow(unused)]
309 /// Used only if an object of this type is returned as a trait impl by a method
310 pub(crate) extern "C" fn MultiThreadedLockableScore_free_void(this_ptr: *mut c_void) {
311         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeMultiThreadedLockableScore) };
312 }
313 #[allow(unused)]
314 impl MultiThreadedLockableScore {
315         pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedLockableScore {
316                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
317         }
318         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedLockableScore {
319                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
320         }
321         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
322         pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedLockableScore {
323                 assert!(self.is_owned);
324                 let ret = ObjOps::untweak_ptr(self.inner);
325                 self.inner = core::ptr::null_mut();
326                 ret
327         }
328 }
329
330 use lightning::routing::scoring::MultiThreadedScoreLock as nativeMultiThreadedScoreLockImport;
331 pub(crate) type nativeMultiThreadedScoreLock = nativeMultiThreadedScoreLockImport<'static, crate::lightning::routing::scoring::Score>;
332
333 /// A locked `MultiThreadedLockableScore`.
334 #[must_use]
335 #[repr(C)]
336 pub struct MultiThreadedScoreLock {
337         /// A pointer to the opaque Rust object.
338
339         /// Nearly everywhere, inner must be non-null, however in places where
340         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
341         pub inner: *mut nativeMultiThreadedScoreLock,
342         /// Indicates that this is the only struct which contains the same pointer.
343
344         /// Rust functions which take ownership of an object provided via an argument require
345         /// this to be true and invalidate the object pointed to by inner.
346         pub is_owned: bool,
347 }
348
349 impl Drop for MultiThreadedScoreLock {
350         fn drop(&mut self) {
351                 if self.is_owned && !<*mut nativeMultiThreadedScoreLock>::is_null(self.inner) {
352                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
353                 }
354         }
355 }
356 /// Frees any resources used by the MultiThreadedScoreLock, if is_owned is set and inner is non-NULL.
357 #[no_mangle]
358 pub extern "C" fn MultiThreadedScoreLock_free(this_obj: MultiThreadedScoreLock) { }
359 #[allow(unused)]
360 /// Used only if an object of this type is returned as a trait impl by a method
361 pub(crate) extern "C" fn MultiThreadedScoreLock_free_void(this_ptr: *mut c_void) {
362         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeMultiThreadedScoreLock) };
363 }
364 #[allow(unused)]
365 impl MultiThreadedScoreLock {
366         pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedScoreLock {
367                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
368         }
369         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedScoreLock {
370                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
371         }
372         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
373         pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedScoreLock {
374                 assert!(self.is_owned);
375                 let ret = ObjOps::untweak_ptr(self.inner);
376                 self.inner = core::ptr::null_mut();
377                 ret
378         }
379 }
380 impl From<nativeMultiThreadedScoreLock> for crate::lightning::routing::scoring::Score {
381         fn from(obj: nativeMultiThreadedScoreLock) -> Self {
382                 let mut rust_obj = MultiThreadedScoreLock { inner: ObjOps::heap_alloc(obj), is_owned: true };
383                 let mut ret = MultiThreadedScoreLock_as_Score(&rust_obj);
384                 // 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
385                 rust_obj.inner = core::ptr::null_mut();
386                 ret.free = Some(MultiThreadedScoreLock_free_void);
387                 ret
388         }
389 }
390 /// Constructs a new Score which calls the relevant methods on this_arg.
391 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
392 #[no_mangle]
393 pub extern "C" fn MultiThreadedScoreLock_as_Score(this_arg: &MultiThreadedScoreLock) -> crate::lightning::routing::scoring::Score {
394         crate::lightning::routing::scoring::Score {
395                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
396                 free: None,
397                 channel_penalty_msat: MultiThreadedScoreLock_Score_channel_penalty_msat,
398                 payment_path_failed: MultiThreadedScoreLock_Score_payment_path_failed,
399                 payment_path_successful: MultiThreadedScoreLock_Score_payment_path_successful,
400                 probe_failed: MultiThreadedScoreLock_Score_probe_failed,
401                 probe_successful: MultiThreadedScoreLock_Score_probe_successful,
402                 write: MultiThreadedScoreLock_write_void,
403         }
404 }
405
406 #[must_use]
407 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 {
408         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()) });
409         ret
410 }
411 extern "C" fn MultiThreadedScoreLock_Score_payment_path_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
412         <nativeMultiThreadedScoreLock as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLock) }, path.get_native_ref(), short_channel_id)
413 }
414 extern "C" fn MultiThreadedScoreLock_Score_payment_path_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
415         <nativeMultiThreadedScoreLock as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLock) }, path.get_native_ref())
416 }
417 extern "C" fn MultiThreadedScoreLock_Score_probe_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
418         <nativeMultiThreadedScoreLock as lightning::routing::scoring::Score<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLock) }, path.get_native_ref(), short_channel_id)
419 }
420 extern "C" fn MultiThreadedScoreLock_Score_probe_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
421         <nativeMultiThreadedScoreLock as lightning::routing::scoring::Score<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLock) }, path.get_native_ref())
422 }
423
424 #[no_mangle]
425 /// Serialize the MultiThreadedScoreLock object into a byte array which can be read by MultiThreadedScoreLock_read
426 pub extern "C" fn MultiThreadedScoreLock_write(obj: &crate::lightning::routing::scoring::MultiThreadedScoreLock) -> crate::c_types::derived::CVec_u8Z {
427         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
428 }
429 #[no_mangle]
430 pub(crate) extern "C" fn MultiThreadedScoreLock_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
431         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeMultiThreadedScoreLock) })
432 }
433 impl From<nativeMultiThreadedLockableScore> for crate::lightning::routing::scoring::LockableScore {
434         fn from(obj: nativeMultiThreadedLockableScore) -> Self {
435                 let mut rust_obj = MultiThreadedLockableScore { inner: ObjOps::heap_alloc(obj), is_owned: true };
436                 let mut ret = MultiThreadedLockableScore_as_LockableScore(&rust_obj);
437                 // 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
438                 rust_obj.inner = core::ptr::null_mut();
439                 ret.free = Some(MultiThreadedLockableScore_free_void);
440                 ret
441         }
442 }
443 /// Constructs a new LockableScore which calls the relevant methods on this_arg.
444 /// This copies the `inner` pointer in this_arg and thus the returned LockableScore must be freed before this_arg is
445 #[no_mangle]
446 pub extern "C" fn MultiThreadedLockableScore_as_LockableScore(this_arg: &MultiThreadedLockableScore) -> crate::lightning::routing::scoring::LockableScore {
447         crate::lightning::routing::scoring::LockableScore {
448                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
449                 free: None,
450                 lock: MultiThreadedLockableScore_LockableScore_lock,
451         }
452 }
453
454 #[must_use]
455 extern "C" fn MultiThreadedLockableScore_LockableScore_lock(this_arg: *const c_void) -> crate::lightning::routing::scoring::Score {
456         let mut ret = <nativeMultiThreadedLockableScore as lightning::routing::scoring::LockableScore<>>::lock(unsafe { &mut *(this_arg as *mut nativeMultiThreadedLockableScore) }, );
457         Into::into(ret)
458 }
459
460 #[no_mangle]
461 /// Serialize the MultiThreadedLockableScore object into a byte array which can be read by MultiThreadedLockableScore_read
462 pub extern "C" fn MultiThreadedLockableScore_write(obj: &crate::lightning::routing::scoring::MultiThreadedLockableScore) -> crate::c_types::derived::CVec_u8Z {
463         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
464 }
465 #[no_mangle]
466 pub(crate) extern "C" fn MultiThreadedLockableScore_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
467         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeMultiThreadedLockableScore) })
468 }
469 impl From<nativeMultiThreadedLockableScore> for crate::lightning::routing::scoring::WriteableScore {
470         fn from(obj: nativeMultiThreadedLockableScore) -> Self {
471                 let mut rust_obj = MultiThreadedLockableScore { inner: ObjOps::heap_alloc(obj), is_owned: true };
472                 let mut ret = MultiThreadedLockableScore_as_WriteableScore(&rust_obj);
473                 // 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
474                 rust_obj.inner = core::ptr::null_mut();
475                 ret.free = Some(MultiThreadedLockableScore_free_void);
476                 ret
477         }
478 }
479 /// Constructs a new WriteableScore which calls the relevant methods on this_arg.
480 /// This copies the `inner` pointer in this_arg and thus the returned WriteableScore must be freed before this_arg is
481 #[no_mangle]
482 pub extern "C" fn MultiThreadedLockableScore_as_WriteableScore(this_arg: &MultiThreadedLockableScore) -> crate::lightning::routing::scoring::WriteableScore {
483         crate::lightning::routing::scoring::WriteableScore {
484                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
485                 free: None,
486                 LockableScore: crate::lightning::routing::scoring::LockableScore {
487                         this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
488                         free: None,
489                         lock: MultiThreadedLockableScore_LockableScore_lock,
490                 },
491                 write: MultiThreadedLockableScore_write_void,
492         }
493 }
494
495
496 /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
497 #[must_use]
498 #[no_mangle]
499 pub extern "C" fn MultiThreadedLockableScore_new(mut score: crate::lightning::routing::scoring::Score) -> crate::lightning::routing::scoring::MultiThreadedLockableScore {
500         let mut ret = lightning::routing::scoring::MultiThreadedLockableScore::new(score);
501         crate::lightning::routing::scoring::MultiThreadedLockableScore { inner: ObjOps::heap_alloc(ret), is_owned: true }
502 }
503
504
505 use lightning::routing::scoring::ChannelUsage as nativeChannelUsageImport;
506 pub(crate) type nativeChannelUsage = nativeChannelUsageImport;
507
508 /// Proposed use of a channel passed as a parameter to [`Score::channel_penalty_msat`].
509 #[must_use]
510 #[repr(C)]
511 pub struct ChannelUsage {
512         /// A pointer to the opaque Rust object.
513
514         /// Nearly everywhere, inner must be non-null, however in places where
515         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
516         pub inner: *mut nativeChannelUsage,
517         /// Indicates that this is the only struct which contains the same pointer.
518
519         /// Rust functions which take ownership of an object provided via an argument require
520         /// this to be true and invalidate the object pointed to by inner.
521         pub is_owned: bool,
522 }
523
524 impl Drop for ChannelUsage {
525         fn drop(&mut self) {
526                 if self.is_owned && !<*mut nativeChannelUsage>::is_null(self.inner) {
527                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
528                 }
529         }
530 }
531 /// Frees any resources used by the ChannelUsage, if is_owned is set and inner is non-NULL.
532 #[no_mangle]
533 pub extern "C" fn ChannelUsage_free(this_obj: ChannelUsage) { }
534 #[allow(unused)]
535 /// Used only if an object of this type is returned as a trait impl by a method
536 pub(crate) extern "C" fn ChannelUsage_free_void(this_ptr: *mut c_void) {
537         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChannelUsage) };
538 }
539 #[allow(unused)]
540 impl ChannelUsage {
541         pub(crate) fn get_native_ref(&self) -> &'static nativeChannelUsage {
542                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
543         }
544         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelUsage {
545                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
546         }
547         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
548         pub(crate) fn take_inner(mut self) -> *mut nativeChannelUsage {
549                 assert!(self.is_owned);
550                 let ret = ObjOps::untweak_ptr(self.inner);
551                 self.inner = core::ptr::null_mut();
552                 ret
553         }
554 }
555 /// The amount to send through the channel, denominated in millisatoshis.
556 #[no_mangle]
557 pub extern "C" fn ChannelUsage_get_amount_msat(this_ptr: &ChannelUsage) -> u64 {
558         let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_msat;
559         *inner_val
560 }
561 /// The amount to send through the channel, denominated in millisatoshis.
562 #[no_mangle]
563 pub extern "C" fn ChannelUsage_set_amount_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
564         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_msat = val;
565 }
566 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
567 /// as part of a multi-path payment.
568 #[no_mangle]
569 pub extern "C" fn ChannelUsage_get_inflight_htlc_msat(this_ptr: &ChannelUsage) -> u64 {
570         let mut inner_val = &mut this_ptr.get_native_mut_ref().inflight_htlc_msat;
571         *inner_val
572 }
573 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
574 /// as part of a multi-path payment.
575 #[no_mangle]
576 pub extern "C" fn ChannelUsage_set_inflight_htlc_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
577         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inflight_htlc_msat = val;
578 }
579 /// The effective capacity of the channel.
580 #[no_mangle]
581 pub extern "C" fn ChannelUsage_get_effective_capacity(this_ptr: &ChannelUsage) -> crate::lightning::routing::gossip::EffectiveCapacity {
582         let mut inner_val = &mut this_ptr.get_native_mut_ref().effective_capacity;
583         crate::lightning::routing::gossip::EffectiveCapacity::from_native(inner_val)
584 }
585 /// The effective capacity of the channel.
586 #[no_mangle]
587 pub extern "C" fn ChannelUsage_set_effective_capacity(this_ptr: &mut ChannelUsage, mut val: crate::lightning::routing::gossip::EffectiveCapacity) {
588         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.effective_capacity = val.into_native();
589 }
590 /// Constructs a new ChannelUsage given each field
591 #[must_use]
592 #[no_mangle]
593 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 {
594         ChannelUsage { inner: ObjOps::heap_alloc(nativeChannelUsage {
595                 amount_msat: amount_msat_arg,
596                 inflight_htlc_msat: inflight_htlc_msat_arg,
597                 effective_capacity: effective_capacity_arg.into_native(),
598         }), is_owned: true }
599 }
600 impl Clone for ChannelUsage {
601         fn clone(&self) -> Self {
602                 Self {
603                         inner: if <*mut nativeChannelUsage>::is_null(self.inner) { core::ptr::null_mut() } else {
604                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
605                         is_owned: true,
606                 }
607         }
608 }
609 #[allow(unused)]
610 /// Used only if an object of this type is returned as a trait impl by a method
611 pub(crate) extern "C" fn ChannelUsage_clone_void(this_ptr: *const c_void) -> *mut c_void {
612         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelUsage)).clone() })) as *mut c_void
613 }
614 #[no_mangle]
615 /// Creates a copy of the ChannelUsage
616 pub extern "C" fn ChannelUsage_clone(orig: &ChannelUsage) -> ChannelUsage {
617         orig.clone()
618 }
619
620 use lightning::routing::scoring::FixedPenaltyScorer as nativeFixedPenaltyScorerImport;
621 pub(crate) type nativeFixedPenaltyScorer = nativeFixedPenaltyScorerImport;
622
623 /// [`Score`] implementation that uses a fixed penalty.
624 #[must_use]
625 #[repr(C)]
626 pub struct FixedPenaltyScorer {
627         /// A pointer to the opaque Rust object.
628
629         /// Nearly everywhere, inner must be non-null, however in places where
630         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
631         pub inner: *mut nativeFixedPenaltyScorer,
632         /// Indicates that this is the only struct which contains the same pointer.
633
634         /// Rust functions which take ownership of an object provided via an argument require
635         /// this to be true and invalidate the object pointed to by inner.
636         pub is_owned: bool,
637 }
638
639 impl Drop for FixedPenaltyScorer {
640         fn drop(&mut self) {
641                 if self.is_owned && !<*mut nativeFixedPenaltyScorer>::is_null(self.inner) {
642                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
643                 }
644         }
645 }
646 /// Frees any resources used by the FixedPenaltyScorer, if is_owned is set and inner is non-NULL.
647 #[no_mangle]
648 pub extern "C" fn FixedPenaltyScorer_free(this_obj: FixedPenaltyScorer) { }
649 #[allow(unused)]
650 /// Used only if an object of this type is returned as a trait impl by a method
651 pub(crate) extern "C" fn FixedPenaltyScorer_free_void(this_ptr: *mut c_void) {
652         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeFixedPenaltyScorer) };
653 }
654 #[allow(unused)]
655 impl FixedPenaltyScorer {
656         pub(crate) fn get_native_ref(&self) -> &'static nativeFixedPenaltyScorer {
657                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
658         }
659         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFixedPenaltyScorer {
660                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
661         }
662         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
663         pub(crate) fn take_inner(mut self) -> *mut nativeFixedPenaltyScorer {
664                 assert!(self.is_owned);
665                 let ret = ObjOps::untweak_ptr(self.inner);
666                 self.inner = core::ptr::null_mut();
667                 ret
668         }
669 }
670 impl Clone for FixedPenaltyScorer {
671         fn clone(&self) -> Self {
672                 Self {
673                         inner: if <*mut nativeFixedPenaltyScorer>::is_null(self.inner) { core::ptr::null_mut() } else {
674                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
675                         is_owned: true,
676                 }
677         }
678 }
679 #[allow(unused)]
680 /// Used only if an object of this type is returned as a trait impl by a method
681 pub(crate) extern "C" fn FixedPenaltyScorer_clone_void(this_ptr: *const c_void) -> *mut c_void {
682         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFixedPenaltyScorer)).clone() })) as *mut c_void
683 }
684 #[no_mangle]
685 /// Creates a copy of the FixedPenaltyScorer
686 pub extern "C" fn FixedPenaltyScorer_clone(orig: &FixedPenaltyScorer) -> FixedPenaltyScorer {
687         orig.clone()
688 }
689 /// Creates a new scorer using `penalty_msat`.
690 #[must_use]
691 #[no_mangle]
692 pub extern "C" fn FixedPenaltyScorer_with_penalty(mut penalty_msat: u64) -> crate::lightning::routing::scoring::FixedPenaltyScorer {
693         let mut ret = lightning::routing::scoring::FixedPenaltyScorer::with_penalty(penalty_msat);
694         crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
695 }
696
697 impl From<nativeFixedPenaltyScorer> for crate::lightning::routing::scoring::Score {
698         fn from(obj: nativeFixedPenaltyScorer) -> Self {
699                 let mut rust_obj = FixedPenaltyScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
700                 let mut ret = FixedPenaltyScorer_as_Score(&rust_obj);
701                 // 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
702                 rust_obj.inner = core::ptr::null_mut();
703                 ret.free = Some(FixedPenaltyScorer_free_void);
704                 ret
705         }
706 }
707 /// Constructs a new Score which calls the relevant methods on this_arg.
708 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
709 #[no_mangle]
710 pub extern "C" fn FixedPenaltyScorer_as_Score(this_arg: &FixedPenaltyScorer) -> crate::lightning::routing::scoring::Score {
711         crate::lightning::routing::scoring::Score {
712                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
713                 free: None,
714                 channel_penalty_msat: FixedPenaltyScorer_Score_channel_penalty_msat,
715                 payment_path_failed: FixedPenaltyScorer_Score_payment_path_failed,
716                 payment_path_successful: FixedPenaltyScorer_Score_payment_path_successful,
717                 probe_failed: FixedPenaltyScorer_Score_probe_failed,
718                 probe_successful: FixedPenaltyScorer_Score_probe_successful,
719                 write: FixedPenaltyScorer_write_void,
720         }
721 }
722
723 #[must_use]
724 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 {
725         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()) });
726         ret
727 }
728 extern "C" fn FixedPenaltyScorer_Score_payment_path_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
729         <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref(), short_channel_id)
730 }
731 extern "C" fn FixedPenaltyScorer_Score_payment_path_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
732         <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref())
733 }
734 extern "C" fn FixedPenaltyScorer_Score_probe_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
735         <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref(), short_channel_id)
736 }
737 extern "C" fn FixedPenaltyScorer_Score_probe_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
738         <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref())
739 }
740
741 #[no_mangle]
742 /// Serialize the FixedPenaltyScorer object into a byte array which can be read by FixedPenaltyScorer_read
743 pub extern "C" fn FixedPenaltyScorer_write(obj: &crate::lightning::routing::scoring::FixedPenaltyScorer) -> crate::c_types::derived::CVec_u8Z {
744         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
745 }
746 #[no_mangle]
747 pub(crate) extern "C" fn FixedPenaltyScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
748         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFixedPenaltyScorer) })
749 }
750 #[no_mangle]
751 /// Read a FixedPenaltyScorer from a byte array, created by FixedPenaltyScorer_write
752 pub extern "C" fn FixedPenaltyScorer_read(ser: crate::c_types::u8slice, arg: u64) -> crate::c_types::derived::CResult_FixedPenaltyScorerDecodeErrorZ {
753         let arg_conv = arg;
754         let res: Result<lightning::routing::scoring::FixedPenaltyScorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
755         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() };
756         local_res
757 }
758
759 use lightning::routing::scoring::ProbabilisticScorer as nativeProbabilisticScorerImport;
760 pub(crate) type nativeProbabilisticScorer = nativeProbabilisticScorerImport<&'static lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger>;
761
762 /// [`Score`] implementation using channel success probability distributions.
763 ///
764 /// Channels are tracked with upper and lower liquidity bounds - when an HTLC fails at a channel,
765 /// we learn that the upper-bound on the available liquidity is lower than the amount of the HTLC.
766 /// When a payment is forwarded through a channel (but fails later in the route), we learn the
767 /// lower-bound on the channel's available liquidity must be at least the value of the HTLC.
768 ///
769 /// These bounds are then used to determine a success probability using the formula from
770 /// *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
771 /// and Stefan Richter [[1]] (i.e. `(upper_bound - payment_amount) / (upper_bound - lower_bound)`).
772 ///
773 /// This probability is combined with the [`liquidity_penalty_multiplier_msat`] and
774 /// [`liquidity_penalty_amount_multiplier_msat`] parameters to calculate a concrete penalty in
775 /// milli-satoshis. The penalties, when added across all hops, have the property of being linear in
776 /// terms of the entire path's success probability. This allows the router to directly compare
777 /// penalties for different paths. See the documentation of those parameters for the exact formulas.
778 ///
779 /// The liquidity bounds are decayed by halving them every [`liquidity_offset_half_life`].
780 ///
781 /// Further, we track the history of our upper and lower liquidity bounds for each channel,
782 /// allowing us to assign a second penalty (using [`historical_liquidity_penalty_multiplier_msat`]
783 /// and [`historical_liquidity_penalty_amount_multiplier_msat`]) based on the same probability
784 /// formula, but using the history of a channel rather than our latest estimates for the liquidity
785 /// bounds.
786 ///
787 /// # Note
788 ///
789 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
790 /// behavior.
791 ///
792 /// [1]: https://arxiv.org/abs/2107.05322
793 /// [`liquidity_penalty_multiplier_msat`]: ProbabilisticScoringParameters::liquidity_penalty_multiplier_msat
794 /// [`liquidity_penalty_amount_multiplier_msat`]: ProbabilisticScoringParameters::liquidity_penalty_amount_multiplier_msat
795 /// [`liquidity_offset_half_life`]: ProbabilisticScoringParameters::liquidity_offset_half_life
796 /// [`historical_liquidity_penalty_multiplier_msat`]: ProbabilisticScoringParameters::historical_liquidity_penalty_multiplier_msat
797 /// [`historical_liquidity_penalty_amount_multiplier_msat`]: ProbabilisticScoringParameters::historical_liquidity_penalty_amount_multiplier_msat
798 #[must_use]
799 #[repr(C)]
800 pub struct ProbabilisticScorer {
801         /// A pointer to the opaque Rust object.
802
803         /// Nearly everywhere, inner must be non-null, however in places where
804         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
805         pub inner: *mut nativeProbabilisticScorer,
806         /// Indicates that this is the only struct which contains the same pointer.
807
808         /// Rust functions which take ownership of an object provided via an argument require
809         /// this to be true and invalidate the object pointed to by inner.
810         pub is_owned: bool,
811 }
812
813 impl Drop for ProbabilisticScorer {
814         fn drop(&mut self) {
815                 if self.is_owned && !<*mut nativeProbabilisticScorer>::is_null(self.inner) {
816                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
817                 }
818         }
819 }
820 /// Frees any resources used by the ProbabilisticScorer, if is_owned is set and inner is non-NULL.
821 #[no_mangle]
822 pub extern "C" fn ProbabilisticScorer_free(this_obj: ProbabilisticScorer) { }
823 #[allow(unused)]
824 /// Used only if an object of this type is returned as a trait impl by a method
825 pub(crate) extern "C" fn ProbabilisticScorer_free_void(this_ptr: *mut c_void) {
826         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeProbabilisticScorer) };
827 }
828 #[allow(unused)]
829 impl ProbabilisticScorer {
830         pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScorer {
831                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
832         }
833         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScorer {
834                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
835         }
836         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
837         pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScorer {
838                 assert!(self.is_owned);
839                 let ret = ObjOps::untweak_ptr(self.inner);
840                 self.inner = core::ptr::null_mut();
841                 ret
842         }
843 }
844
845 use lightning::routing::scoring::ProbabilisticScoringParameters as nativeProbabilisticScoringParametersImport;
846 pub(crate) type nativeProbabilisticScoringParameters = nativeProbabilisticScoringParametersImport;
847
848 /// Parameters for configuring [`ProbabilisticScorer`].
849 ///
850 /// Used to configure base, liquidity, and amount penalties, the sum of which comprises the channel
851 /// penalty (i.e., the amount in msats willing to be paid to avoid routing through the channel).
852 ///
853 /// The penalty applied to any channel by the [`ProbabilisticScorer`] is the sum of each of the
854 /// parameters here.
855 #[must_use]
856 #[repr(C)]
857 pub struct ProbabilisticScoringParameters {
858         /// A pointer to the opaque Rust object.
859
860         /// Nearly everywhere, inner must be non-null, however in places where
861         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
862         pub inner: *mut nativeProbabilisticScoringParameters,
863         /// Indicates that this is the only struct which contains the same pointer.
864
865         /// Rust functions which take ownership of an object provided via an argument require
866         /// this to be true and invalidate the object pointed to by inner.
867         pub is_owned: bool,
868 }
869
870 impl Drop for ProbabilisticScoringParameters {
871         fn drop(&mut self) {
872                 if self.is_owned && !<*mut nativeProbabilisticScoringParameters>::is_null(self.inner) {
873                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
874                 }
875         }
876 }
877 /// Frees any resources used by the ProbabilisticScoringParameters, if is_owned is set and inner is non-NULL.
878 #[no_mangle]
879 pub extern "C" fn ProbabilisticScoringParameters_free(this_obj: ProbabilisticScoringParameters) { }
880 #[allow(unused)]
881 /// Used only if an object of this type is returned as a trait impl by a method
882 pub(crate) extern "C" fn ProbabilisticScoringParameters_free_void(this_ptr: *mut c_void) {
883         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeProbabilisticScoringParameters) };
884 }
885 #[allow(unused)]
886 impl ProbabilisticScoringParameters {
887         pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringParameters {
888                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
889         }
890         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringParameters {
891                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
892         }
893         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
894         pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringParameters {
895                 assert!(self.is_owned);
896                 let ret = ObjOps::untweak_ptr(self.inner);
897                 self.inner = core::ptr::null_mut();
898                 ret
899         }
900 }
901 /// A fixed penalty in msats to apply to each channel.
902 ///
903 /// Default value: 500 msat
904 #[no_mangle]
905 pub extern "C" fn ProbabilisticScoringParameters_get_base_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
906         let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
907         *inner_val
908 }
909 /// A fixed penalty in msats to apply to each channel.
910 ///
911 /// Default value: 500 msat
912 #[no_mangle]
913 pub extern "C" fn ProbabilisticScoringParameters_set_base_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
914         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
915 }
916 /// A multiplier used with the payment amount to calculate a fixed penalty applied to each
917 /// channel, in excess of the [`base_penalty_msat`].
918 ///
919 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
920 /// fees plus penalty) for large payments. The penalty is computed as the product of this
921 /// multiplier and `2^30`ths of the payment amount.
922 ///
923 /// ie `base_penalty_amount_multiplier_msat * amount_msat / 2^30`
924 ///
925 /// Default value: 8,192 msat
926 ///
927 /// [`base_penalty_msat`]: Self::base_penalty_msat
928 #[no_mangle]
929 pub extern "C" fn ProbabilisticScoringParameters_get_base_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
930         let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_amount_multiplier_msat;
931         *inner_val
932 }
933 /// A multiplier used with the payment amount to calculate a fixed penalty applied to each
934 /// channel, in excess of the [`base_penalty_msat`].
935 ///
936 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
937 /// fees plus penalty) for large payments. The penalty is computed as the product of this
938 /// multiplier and `2^30`ths of the payment amount.
939 ///
940 /// ie `base_penalty_amount_multiplier_msat * amount_msat / 2^30`
941 ///
942 /// Default value: 8,192 msat
943 ///
944 /// [`base_penalty_msat`]: Self::base_penalty_msat
945 #[no_mangle]
946 pub extern "C" fn ProbabilisticScoringParameters_set_base_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
947         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_amount_multiplier_msat = val;
948 }
949 /// A multiplier used in conjunction with the negative `log10` of the channel's success
950 /// probability for a payment, as determined by our latest estimates of the channel's
951 /// liquidity, to determine the liquidity penalty.
952 ///
953 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
954 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
955 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
956 /// lower bounding the success probability to `0.01`) when the amount falls within the
957 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
958 /// result in a `u64::max_value` penalty, however.
959 ///
960 /// `-log10(success_probability) * liquidity_penalty_multiplier_msat`
961 ///
962 /// Default value: 30,000 msat
963 ///
964 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
965 #[no_mangle]
966 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
967         let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_multiplier_msat;
968         *inner_val
969 }
970 /// A multiplier used in conjunction with the negative `log10` of the channel's success
971 /// probability for a payment, as determined by our latest estimates of the channel's
972 /// liquidity, to determine the liquidity penalty.
973 ///
974 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
975 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
976 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
977 /// lower bounding the success probability to `0.01`) when the amount falls within the
978 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
979 /// result in a `u64::max_value` penalty, however.
980 ///
981 /// `-log10(success_probability) * liquidity_penalty_multiplier_msat`
982 ///
983 /// Default value: 30,000 msat
984 ///
985 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
986 #[no_mangle]
987 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
988         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_multiplier_msat = val;
989 }
990 /// Whenever this amount of time elapses since the last update to a channel's liquidity bounds,
991 /// the distance from the bounds to \"zero\" is cut in half. In other words, the lower-bound on
992 /// the available liquidity is halved and the upper-bound moves half-way to the channel's total
993 /// capacity.
994 ///
995 /// Because halving the liquidity bounds grows the uncertainty on the channel's liquidity,
996 /// the penalty for an amount within the new bounds may change. See the [`ProbabilisticScorer`]
997 /// struct documentation for more info on the way the liquidity bounds are used.
998 ///
999 /// For example, if the channel's capacity is 1 million sats, and the current upper and lower
1000 /// liquidity bounds are 200,000 sats and 600,000 sats, after this amount of time the upper
1001 /// and lower liquidity bounds will be decayed to 100,000 and 800,000 sats.
1002 ///
1003 /// Default value: 6 hours
1004 ///
1005 /// # Note
1006 ///
1007 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
1008 /// liquidity knowledge will never decay except when the bounds cross.
1009 #[no_mangle]
1010 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_offset_half_life(this_ptr: &ProbabilisticScoringParameters) -> u64 {
1011         let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_offset_half_life;
1012         inner_val.as_secs()
1013 }
1014 /// Whenever this amount of time elapses since the last update to a channel's liquidity bounds,
1015 /// the distance from the bounds to \"zero\" is cut in half. In other words, the lower-bound on
1016 /// the available liquidity is halved and the upper-bound moves half-way to the channel's total
1017 /// capacity.
1018 ///
1019 /// Because halving the liquidity bounds grows the uncertainty on the channel's liquidity,
1020 /// the penalty for an amount within the new bounds may change. See the [`ProbabilisticScorer`]
1021 /// struct documentation for more info on the way the liquidity bounds are used.
1022 ///
1023 /// For example, if the channel's capacity is 1 million sats, and the current upper and lower
1024 /// liquidity bounds are 200,000 sats and 600,000 sats, after this amount of time the upper
1025 /// and lower liquidity bounds will be decayed to 100,000 and 800,000 sats.
1026 ///
1027 /// Default value: 6 hours
1028 ///
1029 /// # Note
1030 ///
1031 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
1032 /// liquidity knowledge will never decay except when the bounds cross.
1033 #[no_mangle]
1034 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_offset_half_life(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
1035         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_offset_half_life = core::time::Duration::from_secs(val);
1036 }
1037 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
1038 /// channel's success probability for the payment, as determined by our latest estimates of the
1039 /// channel's liquidity, to determine the amount penalty.
1040 ///
1041 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
1042 /// fees plus penalty) for large payments. The penalty is computed as the product of this
1043 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
1044 /// success probability.
1045 ///
1046 /// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
1047 ///
1048 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
1049 /// the amount will result in a penalty of the multiplier. And, as the success probability
1050 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
1051 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
1052 /// fall below `1`.
1053 ///
1054 /// Default value: 192 msat
1055 #[no_mangle]
1056 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
1057         let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_amount_multiplier_msat;
1058         *inner_val
1059 }
1060 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
1061 /// channel's success probability for the payment, as determined by our latest estimates of the
1062 /// channel's liquidity, to determine the amount penalty.
1063 ///
1064 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
1065 /// fees plus penalty) for large payments. The penalty is computed as the product of this
1066 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
1067 /// success probability.
1068 ///
1069 /// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
1070 ///
1071 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
1072 /// the amount will result in a penalty of the multiplier. And, as the success probability
1073 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
1074 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
1075 /// fall below `1`.
1076 ///
1077 /// Default value: 192 msat
1078 #[no_mangle]
1079 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
1080         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_amount_multiplier_msat = val;
1081 }
1082 /// A multiplier used in conjunction with the negative `log10` of the channel's success
1083 /// probability for the payment, as determined based on the history of our estimates of the
1084 /// channel's available liquidity, to determine a penalty.
1085 ///
1086 /// This penalty is similar to [`liquidity_penalty_multiplier_msat`], however, instead of using
1087 /// only our latest estimate for the current liquidity available in the channel, it estimates
1088 /// success probability based on the estimated liquidity available in the channel through
1089 /// history. Specifically, every time we update our liquidity bounds on a given channel, we
1090 /// track which of several buckets those bounds fall into, exponentially decaying the
1091 /// probability of each bucket as new samples are added.
1092 ///
1093 /// Default value: 10,000 msat
1094 ///
1095 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1096 #[no_mangle]
1097 pub extern "C" fn ProbabilisticScoringParameters_get_historical_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
1098         let mut inner_val = &mut this_ptr.get_native_mut_ref().historical_liquidity_penalty_multiplier_msat;
1099         *inner_val
1100 }
1101 /// A multiplier used in conjunction with the negative `log10` of the channel's success
1102 /// probability for the payment, as determined based on the history of our estimates of the
1103 /// channel's available liquidity, to determine a penalty.
1104 ///
1105 /// This penalty is similar to [`liquidity_penalty_multiplier_msat`], however, instead of using
1106 /// only our latest estimate for the current liquidity available in the channel, it estimates
1107 /// success probability based on the estimated liquidity available in the channel through
1108 /// history. Specifically, every time we update our liquidity bounds on a given channel, we
1109 /// track which of several buckets those bounds fall into, exponentially decaying the
1110 /// probability of each bucket as new samples are added.
1111 ///
1112 /// Default value: 10,000 msat
1113 ///
1114 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1115 #[no_mangle]
1116 pub extern "C" fn ProbabilisticScoringParameters_set_historical_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
1117         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.historical_liquidity_penalty_multiplier_msat = val;
1118 }
1119 /// A multiplier used in conjunction with the payment amount and the negative `log10` of the
1120 /// channel's success probability for the payment, as determined based on the history of our
1121 /// estimates of the channel's available liquidity, to determine a penalty.
1122 ///
1123 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost for
1124 /// large payments. The penalty is computed as the product of this multiplier and the `2^20`ths
1125 /// of the payment amount, weighted by the negative `log10` of the success probability.
1126 ///
1127 /// This penalty is similar to [`liquidity_penalty_amount_multiplier_msat`], however, instead
1128 /// of using only our latest estimate for the current liquidity available in the channel, it
1129 /// estimates success probability based on the estimated liquidity available in the channel
1130 /// through history. Specifically, every time we update our liquidity bounds on a given
1131 /// channel, we track which of several buckets those bounds fall into, exponentially decaying
1132 /// the probability of each bucket as new samples are added.
1133 ///
1134 /// Default value: 64 msat
1135 ///
1136 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1137 #[no_mangle]
1138 pub extern "C" fn ProbabilisticScoringParameters_get_historical_liquidity_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
1139         let mut inner_val = &mut this_ptr.get_native_mut_ref().historical_liquidity_penalty_amount_multiplier_msat;
1140         *inner_val
1141 }
1142 /// A multiplier used in conjunction with the payment amount and the negative `log10` of the
1143 /// channel's success probability for the payment, as determined based on the history of our
1144 /// estimates of the channel's available liquidity, to determine a penalty.
1145 ///
1146 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost for
1147 /// large payments. The penalty is computed as the product of this multiplier and the `2^20`ths
1148 /// of the payment amount, weighted by the negative `log10` of the success probability.
1149 ///
1150 /// This penalty is similar to [`liquidity_penalty_amount_multiplier_msat`], however, instead
1151 /// of using only our latest estimate for the current liquidity available in the channel, it
1152 /// estimates success probability based on the estimated liquidity available in the channel
1153 /// through history. Specifically, every time we update our liquidity bounds on a given
1154 /// channel, we track which of several buckets those bounds fall into, exponentially decaying
1155 /// the probability of each bucket as new samples are added.
1156 ///
1157 /// Default value: 64 msat
1158 ///
1159 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1160 #[no_mangle]
1161 pub extern "C" fn ProbabilisticScoringParameters_set_historical_liquidity_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
1162         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.historical_liquidity_penalty_amount_multiplier_msat = val;
1163 }
1164 /// If we aren't learning any new datapoints for a channel, the historical liquidity bounds
1165 /// tracking can simply live on with increasingly stale data. Instead, when a channel has not
1166 /// seen a liquidity estimate update for this amount of time, the historical datapoints are
1167 /// decayed by half.
1168 ///
1169 /// Note that after 16 or more half lives all historical data will be completely gone.
1170 ///
1171 /// Default value: 14 days
1172 #[no_mangle]
1173 pub extern "C" fn ProbabilisticScoringParameters_get_historical_no_updates_half_life(this_ptr: &ProbabilisticScoringParameters) -> u64 {
1174         let mut inner_val = &mut this_ptr.get_native_mut_ref().historical_no_updates_half_life;
1175         inner_val.as_secs()
1176 }
1177 /// If we aren't learning any new datapoints for a channel, the historical liquidity bounds
1178 /// tracking can simply live on with increasingly stale data. Instead, when a channel has not
1179 /// seen a liquidity estimate update for this amount of time, the historical datapoints are
1180 /// decayed by half.
1181 ///
1182 /// Note that after 16 or more half lives all historical data will be completely gone.
1183 ///
1184 /// Default value: 14 days
1185 #[no_mangle]
1186 pub extern "C" fn ProbabilisticScoringParameters_set_historical_no_updates_half_life(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
1187         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.historical_no_updates_half_life = core::time::Duration::from_secs(val);
1188 }
1189 /// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
1190 /// channel's capacity, which makes us prefer nodes with a smaller `htlc_maximum_msat`. We
1191 /// treat such nodes preferentially as this makes balance discovery attacks harder to execute,
1192 /// thereby creating an incentive to restrict `htlc_maximum_msat` and improve privacy.
1193 ///
1194 /// Default value: 250 msat
1195 #[no_mangle]
1196 pub extern "C" fn ProbabilisticScoringParameters_get_anti_probing_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
1197         let mut inner_val = &mut this_ptr.get_native_mut_ref().anti_probing_penalty_msat;
1198         *inner_val
1199 }
1200 /// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
1201 /// channel's capacity, which makes us prefer nodes with a smaller `htlc_maximum_msat`. We
1202 /// treat such nodes preferentially as this makes balance discovery attacks harder to execute,
1203 /// thereby creating an incentive to restrict `htlc_maximum_msat` and improve privacy.
1204 ///
1205 /// Default value: 250 msat
1206 #[no_mangle]
1207 pub extern "C" fn ProbabilisticScoringParameters_set_anti_probing_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
1208         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.anti_probing_penalty_msat = val;
1209 }
1210 /// This penalty is applied when the amount we're attempting to send over a channel exceeds our
1211 /// current estimate of the channel's available liquidity.
1212 ///
1213 /// Note that in this case all other penalties, including the
1214 /// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
1215 /// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
1216 /// applicable, are still included in the overall penalty.
1217 ///
1218 /// If you wish to avoid creating paths with such channels entirely, setting this to a value of
1219 /// `u64::max_value()` will guarantee that.
1220 ///
1221 /// Default value: 1_0000_0000_000 msat (1 Bitcoin)
1222 ///
1223 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1224 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1225 /// [`base_penalty_msat`]: Self::base_penalty_msat
1226 /// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
1227 #[no_mangle]
1228 pub extern "C" fn ProbabilisticScoringParameters_get_considered_impossible_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
1229         let mut inner_val = &mut this_ptr.get_native_mut_ref().considered_impossible_penalty_msat;
1230         *inner_val
1231 }
1232 /// This penalty is applied when the amount we're attempting to send over a channel exceeds our
1233 /// current estimate of the channel's available liquidity.
1234 ///
1235 /// Note that in this case all other penalties, including the
1236 /// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
1237 /// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
1238 /// applicable, are still included in the overall penalty.
1239 ///
1240 /// If you wish to avoid creating paths with such channels entirely, setting this to a value of
1241 /// `u64::max_value()` will guarantee that.
1242 ///
1243 /// Default value: 1_0000_0000_000 msat (1 Bitcoin)
1244 ///
1245 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1246 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1247 /// [`base_penalty_msat`]: Self::base_penalty_msat
1248 /// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
1249 #[no_mangle]
1250 pub extern "C" fn ProbabilisticScoringParameters_set_considered_impossible_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
1251         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.considered_impossible_penalty_msat = val;
1252 }
1253 impl Clone for ProbabilisticScoringParameters {
1254         fn clone(&self) -> Self {
1255                 Self {
1256                         inner: if <*mut nativeProbabilisticScoringParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
1257                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
1258                         is_owned: true,
1259                 }
1260         }
1261 }
1262 #[allow(unused)]
1263 /// Used only if an object of this type is returned as a trait impl by a method
1264 pub(crate) extern "C" fn ProbabilisticScoringParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
1265         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeProbabilisticScoringParameters)).clone() })) as *mut c_void
1266 }
1267 #[no_mangle]
1268 /// Creates a copy of the ProbabilisticScoringParameters
1269 pub extern "C" fn ProbabilisticScoringParameters_clone(orig: &ProbabilisticScoringParameters) -> ProbabilisticScoringParameters {
1270         orig.clone()
1271 }
1272 /// Creates a new scorer using the given scoring parameters for sending payments from a node
1273 /// through a network graph.
1274 #[must_use]
1275 #[no_mangle]
1276 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 {
1277         let mut ret = lightning::routing::scoring::ProbabilisticScorer::new(*unsafe { Box::from_raw(params.take_inner()) }, network_graph.get_native_ref(), logger);
1278         crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
1279 }
1280
1281 /// Dump the contents of this scorer into the configured logger.
1282 ///
1283 /// Note that this writes roughly one line per channel for which we have a liquidity estimate,
1284 /// which may be a substantial amount of log output.
1285 #[no_mangle]
1286 pub extern "C" fn ProbabilisticScorer_debug_log_liquidity_stats(this_arg: &crate::lightning::routing::scoring::ProbabilisticScorer) {
1287         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.debug_log_liquidity_stats()
1288 }
1289
1290 /// Query the estimated minimum and maximum liquidity available for sending a payment over the
1291 /// channel with `scid` towards the given `target` node.
1292 #[must_use]
1293 #[no_mangle]
1294 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 {
1295         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.estimated_channel_liquidity_range(scid, target.get_native_ref());
1296         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 }) };
1297         local_ret
1298 }
1299
1300 /// Query the historical estimated minimum and maximum liquidity available for sending a
1301 /// payment over the channel with `scid` towards the given `target` node.
1302 ///
1303 /// Returns two sets of 8 buckets. The first set describes the octiles for lower-bound
1304 /// liquidity estimates, the second set describes the octiles for upper-bound liquidity
1305 /// estimates. Each bucket describes the relative frequency at which we've seen a liquidity
1306 /// bound in the octile relative to the channel's total capacity, on an arbitrary scale.
1307 /// Because the values are slowly decayed, more recent data points are weighted more heavily
1308 /// than older datapoints.
1309 ///
1310 /// When scoring, the estimated probability that an upper-/lower-bound lies in a given octile
1311 /// relative to the channel's total capacity is calculated by dividing that bucket's value with
1312 /// the total of all buckets for the given bound.
1313 ///
1314 /// For example, a value of `[0, 0, 0, 0, 0, 0, 32]` indicates that we believe the probability
1315 /// of a bound being in the top octile to be 100%, and have never (recently) seen it in any
1316 /// other octiles. A value of `[31, 0, 0, 0, 0, 0, 0, 32]` indicates we've seen the bound being
1317 /// both in the top and bottom octile, and roughly with similar (recent) frequency.
1318 ///
1319 /// Because the datapoints are decayed slowly over time, values will eventually return to
1320 /// `Some(([0; 8], [0; 8]))`.
1321 #[must_use]
1322 #[no_mangle]
1323 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_EightU16sEightU16sZZ {
1324         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.historical_estimated_channel_liquidity_probabilities(scid, target.get_native_ref());
1325         let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_C2Tuple_EightU16sEightU16sZZ::None } else { crate::c_types::derived::COption_C2Tuple_EightU16sEightU16sZZ::Some( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (ret.unwrap()); let mut local_ret_0 = (crate::c_types::EightU16s { data: orig_ret_0_0 }, crate::c_types::EightU16s { data: orig_ret_0_1 }).into(); local_ret_0 }) };
1326         local_ret
1327 }
1328
1329 /// Marks the node with the given `node_id` as banned, i.e.,
1330 /// it will be avoided during path finding.
1331 #[no_mangle]
1332 pub extern "C" fn ProbabilisticScorer_add_banned(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer, node_id: &crate::lightning::routing::gossip::NodeId) {
1333         unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.add_banned(node_id.get_native_ref())
1334 }
1335
1336 /// Removes the node with the given `node_id` from the list of nodes to avoid.
1337 #[no_mangle]
1338 pub extern "C" fn ProbabilisticScorer_remove_banned(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer, node_id: &crate::lightning::routing::gossip::NodeId) {
1339         unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.remove_banned(node_id.get_native_ref())
1340 }
1341
1342 /// Sets a manual penalty for the given node.
1343 #[no_mangle]
1344 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) {
1345         unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.set_manual_penalty(node_id.get_native_ref(), penalty)
1346 }
1347
1348 /// Removes the node with the given `node_id` from the list of manual penalties.
1349 #[no_mangle]
1350 pub extern "C" fn ProbabilisticScorer_remove_manual_penalty(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer, node_id: &crate::lightning::routing::gossip::NodeId) {
1351         unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.remove_manual_penalty(node_id.get_native_ref())
1352 }
1353
1354 /// Clears the list of manual penalties that are applied during path finding.
1355 #[no_mangle]
1356 pub extern "C" fn ProbabilisticScorer_clear_manual_penalties(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer) {
1357         unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.clear_manual_penalties()
1358 }
1359
1360 /// Marks all nodes in the given list as banned, i.e.,
1361 /// they will be avoided during path finding.
1362 #[no_mangle]
1363 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) {
1364         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()) } }); };
1365         unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringParameters)) }.add_banned_from_list(local_node_ids)
1366 }
1367
1368 /// Creates a "default" ProbabilisticScoringParameters. See struct and individual field documentaiton for details on which values are used.
1369 #[must_use]
1370 #[no_mangle]
1371 pub extern "C" fn ProbabilisticScoringParameters_default() -> ProbabilisticScoringParameters {
1372         ProbabilisticScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
1373 }
1374 impl From<nativeProbabilisticScorer> for crate::lightning::routing::scoring::Score {
1375         fn from(obj: nativeProbabilisticScorer) -> Self {
1376                 let mut rust_obj = ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
1377                 let mut ret = ProbabilisticScorer_as_Score(&rust_obj);
1378                 // 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
1379                 rust_obj.inner = core::ptr::null_mut();
1380                 ret.free = Some(ProbabilisticScorer_free_void);
1381                 ret
1382         }
1383 }
1384 /// Constructs a new Score which calls the relevant methods on this_arg.
1385 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
1386 #[no_mangle]
1387 pub extern "C" fn ProbabilisticScorer_as_Score(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::Score {
1388         crate::lightning::routing::scoring::Score {
1389                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1390                 free: None,
1391                 channel_penalty_msat: ProbabilisticScorer_Score_channel_penalty_msat,
1392                 payment_path_failed: ProbabilisticScorer_Score_payment_path_failed,
1393                 payment_path_successful: ProbabilisticScorer_Score_payment_path_successful,
1394                 probe_failed: ProbabilisticScorer_Score_probe_failed,
1395                 probe_successful: ProbabilisticScorer_Score_probe_successful,
1396                 write: ProbabilisticScorer_write_void,
1397         }
1398 }
1399
1400 #[must_use]
1401 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 {
1402         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()) });
1403         ret
1404 }
1405 extern "C" fn ProbabilisticScorer_Score_payment_path_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
1406         <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref(), short_channel_id)
1407 }
1408 extern "C" fn ProbabilisticScorer_Score_payment_path_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
1409         <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref())
1410 }
1411 extern "C" fn ProbabilisticScorer_Score_probe_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
1412         <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref(), short_channel_id)
1413 }
1414 extern "C" fn ProbabilisticScorer_Score_probe_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
1415         <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref())
1416 }
1417
1418 mod approx {
1419
1420 use alloc::str::FromStr;
1421 use core::ffi::c_void;
1422 use core::convert::Infallible;
1423 use bitcoin::hashes::Hash;
1424 use crate::c_types::*;
1425 #[cfg(feature="no-std")]
1426 use alloc::{vec::Vec, boxed::Box};
1427
1428 }
1429 #[no_mangle]
1430 /// Serialize the ProbabilisticScorer object into a byte array which can be read by ProbabilisticScorer_read
1431 pub extern "C" fn ProbabilisticScorer_write(obj: &crate::lightning::routing::scoring::ProbabilisticScorer) -> crate::c_types::derived::CVec_u8Z {
1432         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
1433 }
1434 #[no_mangle]
1435 pub(crate) extern "C" fn ProbabilisticScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
1436         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeProbabilisticScorer) })
1437 }
1438 #[no_mangle]
1439 /// Read a ProbabilisticScorer from a byte array, created by ProbabilisticScorer_write
1440 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 {
1441         let arg_a_conv = *unsafe { Box::from_raw(arg_a.take_inner()) };
1442         let arg_b_conv = arg_b.get_native_ref();
1443         let arg_c_conv = arg_c;
1444         let arg_conv = (arg_a_conv, arg_b_conv, arg_c_conv);
1445         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);
1446         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() };
1447         local_res
1448 }