0923a5598d8597308f626539383a3e3812920ace
[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 secp256k1;
18 //! #
19 //! # use lightning::routing::network_graph::NetworkGraph;
20 //! # use lightning::routing::router::{RouteParameters, find_route};
21 //! # use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters, Scorer, ScoringParameters};
22 //! # use lightning::chain::keysinterface::{KeysManager, KeysInterface};
23 //! # use lightning::util::logger::{Logger, Record};
24 //! # use secp256k1::key::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) {
31 //! # let logger = FakeLogger {};
32 //! #
33 //! // Use the default channel penalties.
34 //! let params = ProbabilisticScoringParameters::default();
35 //! let scorer = ProbabilisticScorer::new(params, &network_graph);
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);
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, send_amt_msat: u64, capacity_msat: u64, source: &crate::lightning::routing::network_graph::NodeId, target: &crate::lightning::routing::network_graph::NodeId) -> 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         /// Serialize the object into a byte array
87         pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
88         /// Frees any resources associated with this object given its this_arg pointer.
89         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
90         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
91 }
92 unsafe impl Send for Score {}
93 unsafe impl Sync for Score {}
94 #[no_mangle]
95 pub(crate) extern "C" fn Score_clone_fields(orig: &Score) -> Score {
96         Score {
97                 this_arg: orig.this_arg,
98                 channel_penalty_msat: Clone::clone(&orig.channel_penalty_msat),
99                 payment_path_failed: Clone::clone(&orig.payment_path_failed),
100                 payment_path_successful: Clone::clone(&orig.payment_path_successful),
101                 write: Clone::clone(&orig.write),
102                 free: Clone::clone(&orig.free),
103         }
104 }
105 impl lightning::util::ser::Writeable for Score {
106         fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
107                 let vec = (self.write)(self.this_arg);
108                 w.write_all(vec.as_slice())
109         }
110 }
111
112 use lightning::routing::scoring::Score as rustScore;
113 impl rustScore for Score {
114         fn channel_penalty_msat(&self, mut short_channel_id: u64, mut send_amt_msat: u64, mut capacity_msat: u64, mut source: &lightning::routing::network_graph::NodeId, mut target: &lightning::routing::network_graph::NodeId) -> u64 {
115                 let mut ret = (self.channel_penalty_msat)(self.this_arg, short_channel_id, send_amt_msat, capacity_msat, &crate::lightning::routing::network_graph::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((source as *const lightning::routing::network_graph::NodeId<>) as *mut _) }, is_owned: false }, &crate::lightning::routing::network_graph::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((target as *const lightning::routing::network_graph::NodeId<>) as *mut _) }, is_owned: false });
116                 ret
117         }
118         fn payment_path_failed(&mut self, mut path: &[&lightning::routing::router::RouteHop], mut short_channel_id: u64) {
119                 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 } }); };
120                 (self.payment_path_failed)(self.this_arg, local_path.into(), short_channel_id)
121         }
122         fn payment_path_successful(&mut self, mut path: &[&lightning::routing::router::RouteHop]) {
123                 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 } }); };
124                 (self.payment_path_successful)(self.this_arg, local_path.into())
125         }
126 }
127
128 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
129 // directly as a Deref trait in higher-level structs:
130 impl core::ops::Deref for Score {
131         type Target = Self;
132         fn deref(&self) -> &Self {
133                 self
134         }
135 }
136 /// Calls the free function if one is set
137 #[no_mangle]
138 pub extern "C" fn Score_free(this_ptr: Score) { }
139 impl Drop for Score {
140         fn drop(&mut self) {
141                 if let Some(f) = self.free {
142                         f(self.this_arg);
143                 }
144         }
145 }
146 /// A scorer that is accessed under a lock.
147 ///
148 /// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
149 /// having shared ownership of a scorer but without requiring internal locking in [`Score`]
150 /// implementations. Internal locking would be detrimental to route finding performance and could
151 /// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
152 ///
153 /// [`find_route`]: crate::routing::router::find_route
154 #[repr(C)]
155 pub struct LockableScore {
156         /// An opaque pointer which is passed to your function implementations as an argument.
157         /// This has no meaning in the LDK, and can be NULL or any other value.
158         pub this_arg: *mut c_void,
159         /// Returns the locked scorer.
160         #[must_use]
161         pub lock: extern "C" fn (this_arg: *const c_void) -> crate::lightning::routing::scoring::Score,
162         /// Frees any resources associated with this object given its this_arg pointer.
163         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
164         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
165 }
166 unsafe impl Send for LockableScore {}
167 unsafe impl Sync for LockableScore {}
168 #[no_mangle]
169 pub(crate) extern "C" fn LockableScore_clone_fields(orig: &LockableScore) -> LockableScore {
170         LockableScore {
171                 this_arg: orig.this_arg,
172                 lock: Clone::clone(&orig.lock),
173                 free: Clone::clone(&orig.free),
174         }
175 }
176
177 use lightning::routing::scoring::LockableScore as rustLockableScore;
178 impl<'a> rustLockableScore<'a> for LockableScore {
179         type Locked = crate::lightning::routing::scoring::Score;
180         fn lock(&'a self) -> crate::lightning::routing::scoring::Score {
181                 let mut ret = (self.lock)(self.this_arg);
182                 ret
183         }
184 }
185
186 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
187 // directly as a Deref trait in higher-level structs:
188 impl core::ops::Deref for LockableScore {
189         type Target = Self;
190         fn deref(&self) -> &Self {
191                 self
192         }
193 }
194 /// Calls the free function if one is set
195 #[no_mangle]
196 pub extern "C" fn LockableScore_free(this_ptr: LockableScore) { }
197 impl Drop for LockableScore {
198         fn drop(&mut self) {
199                 if let Some(f) = self.free {
200                         f(self.this_arg);
201                 }
202         }
203 }
204
205 use lightning::routing::scoring::MultiThreadedLockableScore as nativeMultiThreadedLockableScoreImport;
206 pub(crate) type nativeMultiThreadedLockableScore = nativeMultiThreadedLockableScoreImport<crate::lightning::routing::scoring::Score>;
207
208 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
209 #[must_use]
210 #[repr(C)]
211 pub struct MultiThreadedLockableScore {
212         /// A pointer to the opaque Rust object.
213
214         /// Nearly everywhere, inner must be non-null, however in places where
215         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
216         pub inner: *mut nativeMultiThreadedLockableScore,
217         /// Indicates that this is the only struct which contains the same pointer.
218
219         /// Rust functions which take ownership of an object provided via an argument require
220         /// this to be true and invalidate the object pointed to by inner.
221         pub is_owned: bool,
222 }
223
224 impl Drop for MultiThreadedLockableScore {
225         fn drop(&mut self) {
226                 if self.is_owned && !<*mut nativeMultiThreadedLockableScore>::is_null(self.inner) {
227                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
228                 }
229         }
230 }
231 /// Frees any resources used by the MultiThreadedLockableScore, if is_owned is set and inner is non-NULL.
232 #[no_mangle]
233 pub extern "C" fn MultiThreadedLockableScore_free(this_obj: MultiThreadedLockableScore) { }
234 #[allow(unused)]
235 /// Used only if an object of this type is returned as a trait impl by a method
236 pub(crate) extern "C" fn MultiThreadedLockableScore_free_void(this_ptr: *mut c_void) {
237         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMultiThreadedLockableScore); }
238 }
239 #[allow(unused)]
240 impl MultiThreadedLockableScore {
241         pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedLockableScore {
242                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
243         }
244         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedLockableScore {
245                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
246         }
247         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
248         pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedLockableScore {
249                 assert!(self.is_owned);
250                 let ret = ObjOps::untweak_ptr(self.inner);
251                 self.inner = core::ptr::null_mut();
252                 ret
253         }
254 }
255 /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
256 #[must_use]
257 #[no_mangle]
258 pub extern "C" fn MultiThreadedLockableScore_new(mut score: crate::lightning::routing::scoring::Score) -> crate::lightning::routing::scoring::MultiThreadedLockableScore {
259         let mut ret = lightning::routing::scoring::MultiThreadedLockableScore::new(score);
260         crate::lightning::routing::scoring::MultiThreadedLockableScore { inner: ObjOps::heap_alloc(ret), is_owned: true }
261 }
262
263
264 use lightning::routing::scoring::FixedPenaltyScorer as nativeFixedPenaltyScorerImport;
265 pub(crate) type nativeFixedPenaltyScorer = nativeFixedPenaltyScorerImport;
266
267 /// [`Score`] implementation that uses a fixed penalty.
268 #[must_use]
269 #[repr(C)]
270 pub struct FixedPenaltyScorer {
271         /// A pointer to the opaque Rust object.
272
273         /// Nearly everywhere, inner must be non-null, however in places where
274         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
275         pub inner: *mut nativeFixedPenaltyScorer,
276         /// Indicates that this is the only struct which contains the same pointer.
277
278         /// Rust functions which take ownership of an object provided via an argument require
279         /// this to be true and invalidate the object pointed to by inner.
280         pub is_owned: bool,
281 }
282
283 impl Drop for FixedPenaltyScorer {
284         fn drop(&mut self) {
285                 if self.is_owned && !<*mut nativeFixedPenaltyScorer>::is_null(self.inner) {
286                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
287                 }
288         }
289 }
290 /// Frees any resources used by the FixedPenaltyScorer, if is_owned is set and inner is non-NULL.
291 #[no_mangle]
292 pub extern "C" fn FixedPenaltyScorer_free(this_obj: FixedPenaltyScorer) { }
293 #[allow(unused)]
294 /// Used only if an object of this type is returned as a trait impl by a method
295 pub(crate) extern "C" fn FixedPenaltyScorer_free_void(this_ptr: *mut c_void) {
296         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeFixedPenaltyScorer); }
297 }
298 #[allow(unused)]
299 impl FixedPenaltyScorer {
300         pub(crate) fn get_native_ref(&self) -> &'static nativeFixedPenaltyScorer {
301                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
302         }
303         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFixedPenaltyScorer {
304                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
305         }
306         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
307         pub(crate) fn take_inner(mut self) -> *mut nativeFixedPenaltyScorer {
308                 assert!(self.is_owned);
309                 let ret = ObjOps::untweak_ptr(self.inner);
310                 self.inner = core::ptr::null_mut();
311                 ret
312         }
313 }
314 impl Clone for FixedPenaltyScorer {
315         fn clone(&self) -> Self {
316                 Self {
317                         inner: if <*mut nativeFixedPenaltyScorer>::is_null(self.inner) { core::ptr::null_mut() } else {
318                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
319                         is_owned: true,
320                 }
321         }
322 }
323 #[allow(unused)]
324 /// Used only if an object of this type is returned as a trait impl by a method
325 pub(crate) extern "C" fn FixedPenaltyScorer_clone_void(this_ptr: *const c_void) -> *mut c_void {
326         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFixedPenaltyScorer)).clone() })) as *mut c_void
327 }
328 #[no_mangle]
329 /// Creates a copy of the FixedPenaltyScorer
330 pub extern "C" fn FixedPenaltyScorer_clone(orig: &FixedPenaltyScorer) -> FixedPenaltyScorer {
331         orig.clone()
332 }
333 /// Creates a new scorer using `penalty_msat`.
334 #[must_use]
335 #[no_mangle]
336 pub extern "C" fn FixedPenaltyScorer_with_penalty(mut penalty_msat: u64) -> crate::lightning::routing::scoring::FixedPenaltyScorer {
337         let mut ret = lightning::routing::scoring::FixedPenaltyScorer::with_penalty(penalty_msat);
338         crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
339 }
340
341 impl From<nativeFixedPenaltyScorer> for crate::lightning::routing::scoring::Score {
342         fn from(obj: nativeFixedPenaltyScorer) -> Self {
343                 let mut rust_obj = FixedPenaltyScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
344                 let mut ret = FixedPenaltyScorer_as_Score(&rust_obj);
345                 // 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
346                 rust_obj.inner = core::ptr::null_mut();
347                 ret.free = Some(FixedPenaltyScorer_free_void);
348                 ret
349         }
350 }
351 /// Constructs a new Score which calls the relevant methods on this_arg.
352 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
353 #[no_mangle]
354 pub extern "C" fn FixedPenaltyScorer_as_Score(this_arg: &FixedPenaltyScorer) -> crate::lightning::routing::scoring::Score {
355         crate::lightning::routing::scoring::Score {
356                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
357                 free: None,
358                 channel_penalty_msat: FixedPenaltyScorer_Score_channel_penalty_msat,
359                 payment_path_failed: FixedPenaltyScorer_Score_payment_path_failed,
360                 payment_path_successful: FixedPenaltyScorer_Score_payment_path_successful,
361                 write: FixedPenaltyScorer_write_void,
362         }
363 }
364
365 #[must_use]
366 extern "C" fn FixedPenaltyScorer_Score_channel_penalty_msat(this_arg: *const c_void, unused_0: u64, unused_1: u64, unused_2: u64, unused_3: &crate::lightning::routing::network_graph::NodeId, unused_4: &crate::lightning::routing::network_graph::NodeId) -> u64 {
367         let mut ret = <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, unused_0, unused_1, unused_2, unused_3.get_native_ref(), unused_4.get_native_ref());
368         ret
369 }
370 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) {
371         let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
372         <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..], _short_channel_id)
373 }
374 extern "C" fn FixedPenaltyScorer_Score_payment_path_successful(this_arg: *mut c_void, mut _path: crate::c_types::derived::CVec_RouteHopZ) {
375         let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
376         <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..])
377 }
378
379 #[no_mangle]
380 /// Serialize the FixedPenaltyScorer object into a byte array which can be read by FixedPenaltyScorer_read
381 pub extern "C" fn FixedPenaltyScorer_write(obj: &crate::lightning::routing::scoring::FixedPenaltyScorer) -> crate::c_types::derived::CVec_u8Z {
382         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
383 }
384 #[no_mangle]
385 pub(crate) extern "C" fn FixedPenaltyScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
386         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFixedPenaltyScorer) })
387 }
388 #[no_mangle]
389 /// Read a FixedPenaltyScorer from a byte array, created by FixedPenaltyScorer_write
390 pub extern "C" fn FixedPenaltyScorer_read(ser: crate::c_types::u8slice, arg: u64) -> crate::c_types::derived::CResult_FixedPenaltyScorerDecodeErrorZ {
391         let arg_conv = arg;
392         let res: Result<lightning::routing::scoring::FixedPenaltyScorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
393         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
394         local_res
395 }
396
397 use lightning::routing::scoring::Scorer as nativeScorerImport;
398 pub(crate) type nativeScorer = nativeScorerImport;
399
400 /// [`Score`] implementation that provides reasonable default behavior.
401 ///
402 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
403 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
404 ///
405 /// See [module-level documentation] for usage and [`ScoringParameters`] for customization.
406 ///
407 /// # Note
408 ///
409 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
410 /// behavior.
411 ///
412 /// [module-level documentation]: crate::routing::scoring
413 #[must_use]
414 #[repr(C)]
415 pub struct Scorer {
416         /// A pointer to the opaque Rust object.
417
418         /// Nearly everywhere, inner must be non-null, however in places where
419         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
420         pub inner: *mut nativeScorer,
421         /// Indicates that this is the only struct which contains the same pointer.
422
423         /// Rust functions which take ownership of an object provided via an argument require
424         /// this to be true and invalidate the object pointed to by inner.
425         pub is_owned: bool,
426 }
427
428 impl Drop for Scorer {
429         fn drop(&mut self) {
430                 if self.is_owned && !<*mut nativeScorer>::is_null(self.inner) {
431                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
432                 }
433         }
434 }
435 /// Frees any resources used by the Scorer, if is_owned is set and inner is non-NULL.
436 #[no_mangle]
437 pub extern "C" fn Scorer_free(this_obj: Scorer) { }
438 #[allow(unused)]
439 /// Used only if an object of this type is returned as a trait impl by a method
440 pub(crate) extern "C" fn Scorer_free_void(this_ptr: *mut c_void) {
441         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeScorer); }
442 }
443 #[allow(unused)]
444 impl Scorer {
445         pub(crate) fn get_native_ref(&self) -> &'static nativeScorer {
446                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
447         }
448         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeScorer {
449                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
450         }
451         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
452         pub(crate) fn take_inner(mut self) -> *mut nativeScorer {
453                 assert!(self.is_owned);
454                 let ret = ObjOps::untweak_ptr(self.inner);
455                 self.inner = core::ptr::null_mut();
456                 ret
457         }
458 }
459
460 use lightning::routing::scoring::ScoringParameters as nativeScoringParametersImport;
461 pub(crate) type nativeScoringParameters = nativeScoringParametersImport;
462
463 /// Parameters for configuring [`Scorer`].
464 #[must_use]
465 #[repr(C)]
466 pub struct ScoringParameters {
467         /// A pointer to the opaque Rust object.
468
469         /// Nearly everywhere, inner must be non-null, however in places where
470         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
471         pub inner: *mut nativeScoringParameters,
472         /// Indicates that this is the only struct which contains the same pointer.
473
474         /// Rust functions which take ownership of an object provided via an argument require
475         /// this to be true and invalidate the object pointed to by inner.
476         pub is_owned: bool,
477 }
478
479 impl Drop for ScoringParameters {
480         fn drop(&mut self) {
481                 if self.is_owned && !<*mut nativeScoringParameters>::is_null(self.inner) {
482                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
483                 }
484         }
485 }
486 /// Frees any resources used by the ScoringParameters, if is_owned is set and inner is non-NULL.
487 #[no_mangle]
488 pub extern "C" fn ScoringParameters_free(this_obj: ScoringParameters) { }
489 #[allow(unused)]
490 /// Used only if an object of this type is returned as a trait impl by a method
491 pub(crate) extern "C" fn ScoringParameters_free_void(this_ptr: *mut c_void) {
492         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeScoringParameters); }
493 }
494 #[allow(unused)]
495 impl ScoringParameters {
496         pub(crate) fn get_native_ref(&self) -> &'static nativeScoringParameters {
497                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
498         }
499         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeScoringParameters {
500                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
501         }
502         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
503         pub(crate) fn take_inner(mut self) -> *mut nativeScoringParameters {
504                 assert!(self.is_owned);
505                 let ret = ObjOps::untweak_ptr(self.inner);
506                 self.inner = core::ptr::null_mut();
507                 ret
508         }
509 }
510 /// A fixed penalty in msats to apply to each channel.
511 ///
512 /// Default value: 500 msat
513 #[no_mangle]
514 pub extern "C" fn ScoringParameters_get_base_penalty_msat(this_ptr: &ScoringParameters) -> u64 {
515         let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
516         *inner_val
517 }
518 /// A fixed penalty in msats to apply to each channel.
519 ///
520 /// Default value: 500 msat
521 #[no_mangle]
522 pub extern "C" fn ScoringParameters_set_base_penalty_msat(this_ptr: &mut ScoringParameters, mut val: u64) {
523         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
524 }
525 /// A penalty in msats to apply to a channel upon failing to relay a payment.
526 ///
527 /// This accumulates for each failure but may be reduced over time based on
528 /// [`failure_penalty_half_life`] or when successfully routing through a channel.
529 ///
530 /// Default value: 1,024,000 msat
531 ///
532 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
533 #[no_mangle]
534 pub extern "C" fn ScoringParameters_get_failure_penalty_msat(this_ptr: &ScoringParameters) -> u64 {
535         let mut inner_val = &mut this_ptr.get_native_mut_ref().failure_penalty_msat;
536         *inner_val
537 }
538 /// A penalty in msats to apply to a channel upon failing to relay a payment.
539 ///
540 /// This accumulates for each failure but may be reduced over time based on
541 /// [`failure_penalty_half_life`] or when successfully routing through a channel.
542 ///
543 /// Default value: 1,024,000 msat
544 ///
545 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
546 #[no_mangle]
547 pub extern "C" fn ScoringParameters_set_failure_penalty_msat(this_ptr: &mut ScoringParameters, mut val: u64) {
548         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure_penalty_msat = val;
549 }
550 /// When the amount being sent over a channel is this many 1024ths of the total channel
551 /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
552 ///
553 /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
554 ///
555 /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
556 #[no_mangle]
557 pub extern "C" fn ScoringParameters_get_overuse_penalty_start_1024th(this_ptr: &ScoringParameters) -> u16 {
558         let mut inner_val = &mut this_ptr.get_native_mut_ref().overuse_penalty_start_1024th;
559         *inner_val
560 }
561 /// When the amount being sent over a channel is this many 1024ths of the total channel
562 /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
563 ///
564 /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
565 ///
566 /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
567 #[no_mangle]
568 pub extern "C" fn ScoringParameters_set_overuse_penalty_start_1024th(this_ptr: &mut ScoringParameters, mut val: u16) {
569         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.overuse_penalty_start_1024th = val;
570 }
571 /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
572 /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
573 ///
574 /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
575 ///                to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
576 ///
577 /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
578 #[no_mangle]
579 pub extern "C" fn ScoringParameters_get_overuse_penalty_msat_per_1024th(this_ptr: &ScoringParameters) -> u64 {
580         let mut inner_val = &mut this_ptr.get_native_mut_ref().overuse_penalty_msat_per_1024th;
581         *inner_val
582 }
583 /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
584 /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
585 ///
586 /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
587 ///                to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
588 ///
589 /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
590 #[no_mangle]
591 pub extern "C" fn ScoringParameters_set_overuse_penalty_msat_per_1024th(this_ptr: &mut ScoringParameters, mut val: u64) {
592         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.overuse_penalty_msat_per_1024th = val;
593 }
594 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
595 /// cut in half.
596 ///
597 /// Successfully routing through a channel will immediately cut the penalty in half as well.
598 ///
599 /// Default value: 1 hour
600 ///
601 /// # Note
602 ///
603 /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
604 /// never decay.
605 ///
606 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
607 #[no_mangle]
608 pub extern "C" fn ScoringParameters_get_failure_penalty_half_life(this_ptr: &ScoringParameters) -> u64 {
609         let mut inner_val = &mut this_ptr.get_native_mut_ref().failure_penalty_half_life;
610         inner_val.as_secs()
611 }
612 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
613 /// cut in half.
614 ///
615 /// Successfully routing through a channel will immediately cut the penalty in half as well.
616 ///
617 /// Default value: 1 hour
618 ///
619 /// # Note
620 ///
621 /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
622 /// never decay.
623 ///
624 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
625 #[no_mangle]
626 pub extern "C" fn ScoringParameters_set_failure_penalty_half_life(this_ptr: &mut ScoringParameters, mut val: u64) {
627         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure_penalty_half_life = core::time::Duration::from_secs(val);
628 }
629 /// Constructs a new ScoringParameters given each field
630 #[must_use]
631 #[no_mangle]
632 pub extern "C" fn ScoringParameters_new(mut base_penalty_msat_arg: u64, mut failure_penalty_msat_arg: u64, mut overuse_penalty_start_1024th_arg: u16, mut overuse_penalty_msat_per_1024th_arg: u64, mut failure_penalty_half_life_arg: u64) -> ScoringParameters {
633         ScoringParameters { inner: ObjOps::heap_alloc(nativeScoringParameters {
634                 base_penalty_msat: base_penalty_msat_arg,
635                 failure_penalty_msat: failure_penalty_msat_arg,
636                 overuse_penalty_start_1024th: overuse_penalty_start_1024th_arg,
637                 overuse_penalty_msat_per_1024th: overuse_penalty_msat_per_1024th_arg,
638                 failure_penalty_half_life: core::time::Duration::from_secs(failure_penalty_half_life_arg),
639         }), is_owned: true }
640 }
641 impl Clone for ScoringParameters {
642         fn clone(&self) -> Self {
643                 Self {
644                         inner: if <*mut nativeScoringParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
645                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
646                         is_owned: true,
647                 }
648         }
649 }
650 #[allow(unused)]
651 /// Used only if an object of this type is returned as a trait impl by a method
652 pub(crate) extern "C" fn ScoringParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
653         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeScoringParameters)).clone() })) as *mut c_void
654 }
655 #[no_mangle]
656 /// Creates a copy of the ScoringParameters
657 pub extern "C" fn ScoringParameters_clone(orig: &ScoringParameters) -> ScoringParameters {
658         orig.clone()
659 }
660 #[no_mangle]
661 /// Serialize the ScoringParameters object into a byte array which can be read by ScoringParameters_read
662 pub extern "C" fn ScoringParameters_write(obj: &crate::lightning::routing::scoring::ScoringParameters) -> crate::c_types::derived::CVec_u8Z {
663         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
664 }
665 #[no_mangle]
666 pub(crate) extern "C" fn ScoringParameters_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
667         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeScoringParameters) })
668 }
669 #[no_mangle]
670 /// Read a ScoringParameters from a byte array, created by ScoringParameters_write
671 pub extern "C" fn ScoringParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ScoringParametersDecodeErrorZ {
672         let res: Result<lightning::routing::scoring::ScoringParameters, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
673         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scoring::ScoringParameters { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
674         local_res
675 }
676 /// Creates a new scorer using the given scoring parameters.
677 #[must_use]
678 #[no_mangle]
679 pub extern "C" fn Scorer_new(mut params: crate::lightning::routing::scoring::ScoringParameters) -> crate::lightning::routing::scoring::Scorer {
680         let mut ret = lightning::routing::scoring::Scorer::new(*unsafe { Box::from_raw(params.take_inner()) });
681         crate::lightning::routing::scoring::Scorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
682 }
683
684 /// Creates a "default" Scorer. See struct and individual field documentaiton for details on which values are used.
685 #[must_use]
686 #[no_mangle]
687 pub extern "C" fn Scorer_default() -> Scorer {
688         Scorer { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
689 }
690 /// Creates a "default" ScoringParameters. See struct and individual field documentaiton for details on which values are used.
691 #[must_use]
692 #[no_mangle]
693 pub extern "C" fn ScoringParameters_default() -> ScoringParameters {
694         ScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
695 }
696 impl From<nativeScorer> for crate::lightning::routing::scoring::Score {
697         fn from(obj: nativeScorer) -> Self {
698                 let mut rust_obj = Scorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
699                 let mut ret = Scorer_as_Score(&rust_obj);
700                 // 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
701                 rust_obj.inner = core::ptr::null_mut();
702                 ret.free = Some(Scorer_free_void);
703                 ret
704         }
705 }
706 /// Constructs a new Score which calls the relevant methods on this_arg.
707 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
708 #[no_mangle]
709 pub extern "C" fn Scorer_as_Score(this_arg: &Scorer) -> crate::lightning::routing::scoring::Score {
710         crate::lightning::routing::scoring::Score {
711                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
712                 free: None,
713                 channel_penalty_msat: Scorer_Score_channel_penalty_msat,
714                 payment_path_failed: Scorer_Score_payment_path_failed,
715                 payment_path_successful: Scorer_Score_payment_path_successful,
716                 write: Scorer_write_void,
717         }
718 }
719
720 #[must_use]
721 extern "C" fn Scorer_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, mut send_amt_msat: u64, mut capacity_msat: u64, _source: &crate::lightning::routing::network_graph::NodeId, _target: &crate::lightning::routing::network_graph::NodeId) -> u64 {
722         let mut ret = <nativeScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeScorer) }, short_channel_id, send_amt_msat, capacity_msat, _source.get_native_ref(), _target.get_native_ref());
723         ret
724 }
725 extern "C" fn Scorer_Score_payment_path_failed(this_arg: *mut c_void, mut _path: crate::c_types::derived::CVec_RouteHopZ, mut short_channel_id: u64) {
726         let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
727         <nativeScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeScorer) }, &local__path[..], short_channel_id)
728 }
729 extern "C" fn Scorer_Score_payment_path_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
730         let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
731         <nativeScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeScorer) }, &local_path[..])
732 }
733
734 #[no_mangle]
735 /// Serialize the Scorer object into a byte array which can be read by Scorer_read
736 pub extern "C" fn Scorer_write(obj: &crate::lightning::routing::scoring::Scorer) -> crate::c_types::derived::CVec_u8Z {
737         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
738 }
739 #[no_mangle]
740 pub(crate) extern "C" fn Scorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
741         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeScorer) })
742 }
743 #[no_mangle]
744 /// Read a Scorer from a byte array, created by Scorer_write
745 pub extern "C" fn Scorer_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ScorerDecodeErrorZ {
746         let res: Result<lightning::routing::scoring::Scorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
747         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scoring::Scorer { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
748         local_res
749 }
750
751 use lightning::routing::scoring::ProbabilisticScorer as nativeProbabilisticScorerImport;
752 pub(crate) type nativeProbabilisticScorer = nativeProbabilisticScorerImport<&'static lightning::routing::network_graph::NetworkGraph>;
753
754 /// [`Score`] implementation using channel success probability distributions.
755 ///
756 /// Based on *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
757 /// and Stefan Richter [[1]]. Given the uncertainty of channel liquidity balances, probability
758 /// distributions are defined based on knowledge learned from successful and unsuccessful attempts.
759 /// Then the negative `log10` of the success probability is used to determine the cost of routing a
760 /// specific HTLC amount through a channel.
761 ///
762 /// Knowledge about channel liquidity balances takes the form of upper and lower bounds on the
763 /// possible liquidity. Certainty of the bounds is decreased over time using a decay function. See
764 /// [`ProbabilisticScoringParameters`] for details.
765 ///
766 /// Since the scorer aims to learn the current channel liquidity balances, it works best for nodes
767 /// with high payment volume or that actively probe the [`NetworkGraph`]. Nodes with low payment
768 /// volume are more likely to experience failed payment paths, which would need to be retried.
769 ///
770 /// # Note
771 ///
772 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
773 /// behavior.
774 ///
775 /// [1]: https://arxiv.org/abs/2107.05322
776 #[must_use]
777 #[repr(C)]
778 pub struct ProbabilisticScorer {
779         /// A pointer to the opaque Rust object.
780
781         /// Nearly everywhere, inner must be non-null, however in places where
782         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
783         pub inner: *mut nativeProbabilisticScorer,
784         /// Indicates that this is the only struct which contains the same pointer.
785
786         /// Rust functions which take ownership of an object provided via an argument require
787         /// this to be true and invalidate the object pointed to by inner.
788         pub is_owned: bool,
789 }
790
791 impl Drop for ProbabilisticScorer {
792         fn drop(&mut self) {
793                 if self.is_owned && !<*mut nativeProbabilisticScorer>::is_null(self.inner) {
794                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
795                 }
796         }
797 }
798 /// Frees any resources used by the ProbabilisticScorer, if is_owned is set and inner is non-NULL.
799 #[no_mangle]
800 pub extern "C" fn ProbabilisticScorer_free(this_obj: ProbabilisticScorer) { }
801 #[allow(unused)]
802 /// Used only if an object of this type is returned as a trait impl by a method
803 pub(crate) extern "C" fn ProbabilisticScorer_free_void(this_ptr: *mut c_void) {
804         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScorer); }
805 }
806 #[allow(unused)]
807 impl ProbabilisticScorer {
808         pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScorer {
809                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
810         }
811         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScorer {
812                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
813         }
814         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
815         pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScorer {
816                 assert!(self.is_owned);
817                 let ret = ObjOps::untweak_ptr(self.inner);
818                 self.inner = core::ptr::null_mut();
819                 ret
820         }
821 }
822
823 use lightning::routing::scoring::ProbabilisticScoringParameters as nativeProbabilisticScoringParametersImport;
824 pub(crate) type nativeProbabilisticScoringParameters = nativeProbabilisticScoringParametersImport;
825
826 /// Parameters for configuring [`ProbabilisticScorer`].
827 ///
828 /// Used to configure base, liquidity, and amount penalties, the sum of which comprises the channel
829 /// penalty (i.e., the amount in msats willing to be paid to avoid routing through the channel).
830 #[must_use]
831 #[repr(C)]
832 pub struct ProbabilisticScoringParameters {
833         /// A pointer to the opaque Rust object.
834
835         /// Nearly everywhere, inner must be non-null, however in places where
836         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
837         pub inner: *mut nativeProbabilisticScoringParameters,
838         /// Indicates that this is the only struct which contains the same pointer.
839
840         /// Rust functions which take ownership of an object provided via an argument require
841         /// this to be true and invalidate the object pointed to by inner.
842         pub is_owned: bool,
843 }
844
845 impl Drop for ProbabilisticScoringParameters {
846         fn drop(&mut self) {
847                 if self.is_owned && !<*mut nativeProbabilisticScoringParameters>::is_null(self.inner) {
848                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
849                 }
850         }
851 }
852 /// Frees any resources used by the ProbabilisticScoringParameters, if is_owned is set and inner is non-NULL.
853 #[no_mangle]
854 pub extern "C" fn ProbabilisticScoringParameters_free(this_obj: ProbabilisticScoringParameters) { }
855 #[allow(unused)]
856 /// Used only if an object of this type is returned as a trait impl by a method
857 pub(crate) extern "C" fn ProbabilisticScoringParameters_free_void(this_ptr: *mut c_void) {
858         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScoringParameters); }
859 }
860 #[allow(unused)]
861 impl ProbabilisticScoringParameters {
862         pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringParameters {
863                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
864         }
865         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringParameters {
866                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
867         }
868         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
869         pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringParameters {
870                 assert!(self.is_owned);
871                 let ret = ObjOps::untweak_ptr(self.inner);
872                 self.inner = core::ptr::null_mut();
873                 ret
874         }
875 }
876 /// A fixed penalty in msats to apply to each channel.
877 ///
878 /// Default value: 500 msat
879 #[no_mangle]
880 pub extern "C" fn ProbabilisticScoringParameters_get_base_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
881         let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
882         *inner_val
883 }
884 /// A fixed penalty in msats to apply to each channel.
885 ///
886 /// Default value: 500 msat
887 #[no_mangle]
888 pub extern "C" fn ProbabilisticScoringParameters_set_base_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
889         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
890 }
891 /// A multiplier used in conjunction with the negative `log10` of the channel's success
892 /// probability for a payment to determine the liquidity penalty.
893 ///
894 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
895 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
896 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
897 /// lower bounding the success probability to `0.01`) when the amount falls within the
898 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
899 /// result in a `u64::max_value` penalty, however.
900 ///
901 /// Default value: 40,000 msat
902 ///
903 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
904 #[no_mangle]
905 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
906         let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_multiplier_msat;
907         *inner_val
908 }
909 /// A multiplier used in conjunction with the negative `log10` of the channel's success
910 /// probability for a payment to determine the liquidity penalty.
911 ///
912 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
913 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
914 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
915 /// lower bounding the success probability to `0.01`) when the amount falls within the
916 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
917 /// result in a `u64::max_value` penalty, however.
918 ///
919 /// Default value: 40,000 msat
920 ///
921 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
922 #[no_mangle]
923 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
924         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_multiplier_msat = val;
925 }
926 /// The time required to elapse before any knowledge learned about channel liquidity balances is
927 /// cut in half.
928 ///
929 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
930 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
931 /// the certainty of the channel liquidity balance.
932 ///
933 /// Default value: 1 hour
934 ///
935 /// # Note
936 ///
937 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
938 /// liquidity knowledge will never decay except when the bounds cross.
939 #[no_mangle]
940 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_offset_half_life(this_ptr: &ProbabilisticScoringParameters) -> u64 {
941         let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_offset_half_life;
942         inner_val.as_secs()
943 }
944 /// The time required to elapse before any knowledge learned about channel liquidity balances is
945 /// cut in half.
946 ///
947 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
948 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
949 /// the certainty of the channel liquidity balance.
950 ///
951 /// Default value: 1 hour
952 ///
953 /// # Note
954 ///
955 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
956 /// liquidity knowledge will never decay except when the bounds cross.
957 #[no_mangle]
958 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_offset_half_life(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
959         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_offset_half_life = core::time::Duration::from_secs(val);
960 }
961 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
962 /// channel's success probability for the payment to determine the amount penalty.
963 ///
964 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
965 /// fees plus penalty) for large payments. The penalty is computed as the product of this
966 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
967 /// success probability.
968 ///
969 /// `-log10(success_probability) * amount_penalty_multiplier_msat * amount_msat / 2^20`
970 ///
971 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
972 /// the amount will result in a penalty of the multiplier. And, as the success probability
973 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
974 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
975 /// fall below `1`.
976 ///
977 /// Default value: 256 msat
978 #[no_mangle]
979 pub extern "C" fn ProbabilisticScoringParameters_get_amount_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
980         let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_penalty_multiplier_msat;
981         *inner_val
982 }
983 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
984 /// channel's success probability for the payment to determine the amount penalty.
985 ///
986 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
987 /// fees plus penalty) for large payments. The penalty is computed as the product of this
988 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
989 /// success probability.
990 ///
991 /// `-log10(success_probability) * amount_penalty_multiplier_msat * amount_msat / 2^20`
992 ///
993 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
994 /// the amount will result in a penalty of the multiplier. And, as the success probability
995 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
996 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
997 /// fall below `1`.
998 ///
999 /// Default value: 256 msat
1000 #[no_mangle]
1001 pub extern "C" fn ProbabilisticScoringParameters_set_amount_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
1002         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_penalty_multiplier_msat = val;
1003 }
1004 /// Constructs a new ProbabilisticScoringParameters given each field
1005 #[must_use]
1006 #[no_mangle]
1007 pub extern "C" fn ProbabilisticScoringParameters_new(mut base_penalty_msat_arg: u64, mut liquidity_penalty_multiplier_msat_arg: u64, mut liquidity_offset_half_life_arg: u64, mut amount_penalty_multiplier_msat_arg: u64) -> ProbabilisticScoringParameters {
1008         ProbabilisticScoringParameters { inner: ObjOps::heap_alloc(nativeProbabilisticScoringParameters {
1009                 base_penalty_msat: base_penalty_msat_arg,
1010                 liquidity_penalty_multiplier_msat: liquidity_penalty_multiplier_msat_arg,
1011                 liquidity_offset_half_life: core::time::Duration::from_secs(liquidity_offset_half_life_arg),
1012                 amount_penalty_multiplier_msat: amount_penalty_multiplier_msat_arg,
1013         }), is_owned: true }
1014 }
1015 impl Clone for ProbabilisticScoringParameters {
1016         fn clone(&self) -> Self {
1017                 Self {
1018                         inner: if <*mut nativeProbabilisticScoringParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
1019                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
1020                         is_owned: true,
1021                 }
1022         }
1023 }
1024 #[allow(unused)]
1025 /// Used only if an object of this type is returned as a trait impl by a method
1026 pub(crate) extern "C" fn ProbabilisticScoringParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
1027         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeProbabilisticScoringParameters)).clone() })) as *mut c_void
1028 }
1029 #[no_mangle]
1030 /// Creates a copy of the ProbabilisticScoringParameters
1031 pub extern "C" fn ProbabilisticScoringParameters_clone(orig: &ProbabilisticScoringParameters) -> ProbabilisticScoringParameters {
1032         orig.clone()
1033 }
1034 /// Creates a new scorer using the given scoring parameters for sending payments from a node
1035 /// through a network graph.
1036 #[must_use]
1037 #[no_mangle]
1038 pub extern "C" fn ProbabilisticScorer_new(mut params: crate::lightning::routing::scoring::ProbabilisticScoringParameters, network_graph: &crate::lightning::routing::network_graph::NetworkGraph) -> crate::lightning::routing::scoring::ProbabilisticScorer {
1039         let mut ret = lightning::routing::scoring::ProbabilisticScorer::new(*unsafe { Box::from_raw(params.take_inner()) }, network_graph.get_native_ref());
1040         crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
1041 }
1042
1043 /// Creates a "default" ProbabilisticScoringParameters. See struct and individual field documentaiton for details on which values are used.
1044 #[must_use]
1045 #[no_mangle]
1046 pub extern "C" fn ProbabilisticScoringParameters_default() -> ProbabilisticScoringParameters {
1047         ProbabilisticScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
1048 }
1049 impl From<nativeProbabilisticScorer> for crate::lightning::routing::scoring::Score {
1050         fn from(obj: nativeProbabilisticScorer) -> Self {
1051                 let mut rust_obj = ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
1052                 let mut ret = ProbabilisticScorer_as_Score(&rust_obj);
1053                 // 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
1054                 rust_obj.inner = core::ptr::null_mut();
1055                 ret.free = Some(ProbabilisticScorer_free_void);
1056                 ret
1057         }
1058 }
1059 /// Constructs a new Score which calls the relevant methods on this_arg.
1060 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
1061 #[no_mangle]
1062 pub extern "C" fn ProbabilisticScorer_as_Score(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::Score {
1063         crate::lightning::routing::scoring::Score {
1064                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1065                 free: None,
1066                 channel_penalty_msat: ProbabilisticScorer_Score_channel_penalty_msat,
1067                 payment_path_failed: ProbabilisticScorer_Score_payment_path_failed,
1068                 payment_path_successful: ProbabilisticScorer_Score_payment_path_successful,
1069                 write: ProbabilisticScorer_write_void,
1070         }
1071 }
1072
1073 #[must_use]
1074 extern "C" fn ProbabilisticScorer_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, mut amount_msat: u64, mut capacity_msat: u64, source: &crate::lightning::routing::network_graph::NodeId, target: &crate::lightning::routing::network_graph::NodeId) -> u64 {
1075         let mut ret = <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, short_channel_id, amount_msat, capacity_msat, source.get_native_ref(), target.get_native_ref());
1076         ret
1077 }
1078 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) {
1079         let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1080         <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..], short_channel_id)
1081 }
1082 extern "C" fn ProbabilisticScorer_Score_payment_path_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
1083         let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1084         <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..])
1085 }
1086
1087 mod approx {
1088
1089 use alloc::str::FromStr;
1090 use core::ffi::c_void;
1091 use core::convert::Infallible;
1092 use bitcoin::hashes::Hash;
1093 use crate::c_types::*;
1094 #[cfg(feature="no-std")]
1095 use alloc::{vec::Vec, boxed::Box};
1096
1097 }
1098 #[no_mangle]
1099 /// Serialize the ProbabilisticScorer object into a byte array which can be read by ProbabilisticScorer_read
1100 pub extern "C" fn ProbabilisticScorer_write(obj: &crate::lightning::routing::scoring::ProbabilisticScorer) -> crate::c_types::derived::CVec_u8Z {
1101         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
1102 }
1103 #[no_mangle]
1104 pub(crate) extern "C" fn ProbabilisticScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
1105         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeProbabilisticScorer) })
1106 }
1107 #[no_mangle]
1108 /// Read a ProbabilisticScorer from a byte array, created by ProbabilisticScorer_write
1109 pub extern "C" fn ProbabilisticScorer_read(ser: crate::c_types::u8slice, arg_a: crate::lightning::routing::scoring::ProbabilisticScoringParameters, arg_b: &crate::lightning::routing::network_graph::NetworkGraph) -> crate::c_types::derived::CResult_ProbabilisticScorerDecodeErrorZ {
1110         let arg_a_conv = *unsafe { Box::from_raw(arg_a.take_inner()) };
1111         let arg_b_conv = arg_b.get_native_ref();
1112         let arg_conv = (arg_a_conv, arg_b_conv);
1113         let res: Result<lightning::routing::scoring::ProbabilisticScorer<&lightning::routing::network_graph::NetworkGraph>, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
1114         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
1115         local_res
1116 }
1117 mod time {
1118
1119 use alloc::str::FromStr;
1120 use core::ffi::c_void;
1121 use core::convert::Infallible;
1122 use bitcoin::hashes::Hash;
1123 use crate::c_types::*;
1124 #[cfg(feature="no-std")]
1125 use alloc::{vec::Vec, boxed::Box};
1126
1127 }