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