Update auto-generated bindings to LDK 0.0.110
[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, KeysInterface};
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
219 use lightning::routing::scoring::MultiThreadedLockableScore as nativeMultiThreadedLockableScoreImport;
220 pub(crate) type nativeMultiThreadedLockableScore = nativeMultiThreadedLockableScoreImport<crate::lightning::routing::scoring::Score>;
221
222 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
223 #[must_use]
224 #[repr(C)]
225 pub struct MultiThreadedLockableScore {
226         /// A pointer to the opaque Rust object.
227
228         /// Nearly everywhere, inner must be non-null, however in places where
229         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
230         pub inner: *mut nativeMultiThreadedLockableScore,
231         /// Indicates that this is the only struct which contains the same pointer.
232
233         /// Rust functions which take ownership of an object provided via an argument require
234         /// this to be true and invalidate the object pointed to by inner.
235         pub is_owned: bool,
236 }
237
238 impl Drop for MultiThreadedLockableScore {
239         fn drop(&mut self) {
240                 if self.is_owned && !<*mut nativeMultiThreadedLockableScore>::is_null(self.inner) {
241                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
242                 }
243         }
244 }
245 /// Frees any resources used by the MultiThreadedLockableScore, if is_owned is set and inner is non-NULL.
246 #[no_mangle]
247 pub extern "C" fn MultiThreadedLockableScore_free(this_obj: MultiThreadedLockableScore) { }
248 #[allow(unused)]
249 /// Used only if an object of this type is returned as a trait impl by a method
250 pub(crate) extern "C" fn MultiThreadedLockableScore_free_void(this_ptr: *mut c_void) {
251         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMultiThreadedLockableScore); }
252 }
253 #[allow(unused)]
254 impl MultiThreadedLockableScore {
255         pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedLockableScore {
256                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
257         }
258         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedLockableScore {
259                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
260         }
261         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
262         pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedLockableScore {
263                 assert!(self.is_owned);
264                 let ret = ObjOps::untweak_ptr(self.inner);
265                 self.inner = core::ptr::null_mut();
266                 ret
267         }
268 }
269 #[no_mangle]
270 /// Serialize the MultiThreadedLockableScore object into a byte array which can be read by MultiThreadedLockableScore_read
271 pub extern "C" fn MultiThreadedLockableScore_write(obj: &crate::lightning::routing::scoring::MultiThreadedLockableScore) -> crate::c_types::derived::CVec_u8Z {
272         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
273 }
274 #[no_mangle]
275 pub(crate) extern "C" fn MultiThreadedLockableScore_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
276         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeMultiThreadedLockableScore) })
277 }
278 /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
279 #[must_use]
280 #[no_mangle]
281 pub extern "C" fn MultiThreadedLockableScore_new(mut score: crate::lightning::routing::scoring::Score) -> crate::lightning::routing::scoring::MultiThreadedLockableScore {
282         let mut ret = lightning::routing::scoring::MultiThreadedLockableScore::new(score);
283         crate::lightning::routing::scoring::MultiThreadedLockableScore { inner: ObjOps::heap_alloc(ret), is_owned: true }
284 }
285
286
287 use lightning::routing::scoring::ChannelUsage as nativeChannelUsageImport;
288 pub(crate) type nativeChannelUsage = nativeChannelUsageImport;
289
290 /// Proposed use of a channel passed as a parameter to [`Score::channel_penalty_msat`].
291 #[must_use]
292 #[repr(C)]
293 pub struct ChannelUsage {
294         /// A pointer to the opaque Rust object.
295
296         /// Nearly everywhere, inner must be non-null, however in places where
297         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
298         pub inner: *mut nativeChannelUsage,
299         /// Indicates that this is the only struct which contains the same pointer.
300
301         /// Rust functions which take ownership of an object provided via an argument require
302         /// this to be true and invalidate the object pointed to by inner.
303         pub is_owned: bool,
304 }
305
306 impl Drop for ChannelUsage {
307         fn drop(&mut self) {
308                 if self.is_owned && !<*mut nativeChannelUsage>::is_null(self.inner) {
309                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
310                 }
311         }
312 }
313 /// Frees any resources used by the ChannelUsage, if is_owned is set and inner is non-NULL.
314 #[no_mangle]
315 pub extern "C" fn ChannelUsage_free(this_obj: ChannelUsage) { }
316 #[allow(unused)]
317 /// Used only if an object of this type is returned as a trait impl by a method
318 pub(crate) extern "C" fn ChannelUsage_free_void(this_ptr: *mut c_void) {
319         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelUsage); }
320 }
321 #[allow(unused)]
322 impl ChannelUsage {
323         pub(crate) fn get_native_ref(&self) -> &'static nativeChannelUsage {
324                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
325         }
326         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelUsage {
327                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
328         }
329         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
330         pub(crate) fn take_inner(mut self) -> *mut nativeChannelUsage {
331                 assert!(self.is_owned);
332                 let ret = ObjOps::untweak_ptr(self.inner);
333                 self.inner = core::ptr::null_mut();
334                 ret
335         }
336 }
337 /// The amount to send through the channel, denominated in millisatoshis.
338 #[no_mangle]
339 pub extern "C" fn ChannelUsage_get_amount_msat(this_ptr: &ChannelUsage) -> u64 {
340         let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_msat;
341         *inner_val
342 }
343 /// The amount to send through the channel, denominated in millisatoshis.
344 #[no_mangle]
345 pub extern "C" fn ChannelUsage_set_amount_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
346         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_msat = val;
347 }
348 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
349 /// as part of a multi-path payment.
350 #[no_mangle]
351 pub extern "C" fn ChannelUsage_get_inflight_htlc_msat(this_ptr: &ChannelUsage) -> u64 {
352         let mut inner_val = &mut this_ptr.get_native_mut_ref().inflight_htlc_msat;
353         *inner_val
354 }
355 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
356 /// as part of a multi-path payment.
357 #[no_mangle]
358 pub extern "C" fn ChannelUsage_set_inflight_htlc_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
359         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inflight_htlc_msat = val;
360 }
361 /// The effective capacity of the channel.
362 #[no_mangle]
363 pub extern "C" fn ChannelUsage_get_effective_capacity(this_ptr: &ChannelUsage) -> crate::lightning::routing::gossip::EffectiveCapacity {
364         let mut inner_val = &mut this_ptr.get_native_mut_ref().effective_capacity;
365         crate::lightning::routing::gossip::EffectiveCapacity::from_native(inner_val)
366 }
367 /// The effective capacity of the channel.
368 #[no_mangle]
369 pub extern "C" fn ChannelUsage_set_effective_capacity(this_ptr: &mut ChannelUsage, mut val: crate::lightning::routing::gossip::EffectiveCapacity) {
370         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.effective_capacity = val.into_native();
371 }
372 /// Constructs a new ChannelUsage given each field
373 #[must_use]
374 #[no_mangle]
375 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 {
376         ChannelUsage { inner: ObjOps::heap_alloc(nativeChannelUsage {
377                 amount_msat: amount_msat_arg,
378                 inflight_htlc_msat: inflight_htlc_msat_arg,
379                 effective_capacity: effective_capacity_arg.into_native(),
380         }), is_owned: true }
381 }
382 impl Clone for ChannelUsage {
383         fn clone(&self) -> Self {
384                 Self {
385                         inner: if <*mut nativeChannelUsage>::is_null(self.inner) { core::ptr::null_mut() } else {
386                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
387                         is_owned: true,
388                 }
389         }
390 }
391 #[allow(unused)]
392 /// Used only if an object of this type is returned as a trait impl by a method
393 pub(crate) extern "C" fn ChannelUsage_clone_void(this_ptr: *const c_void) -> *mut c_void {
394         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelUsage)).clone() })) as *mut c_void
395 }
396 #[no_mangle]
397 /// Creates a copy of the ChannelUsage
398 pub extern "C" fn ChannelUsage_clone(orig: &ChannelUsage) -> ChannelUsage {
399         orig.clone()
400 }
401
402 use lightning::routing::scoring::FixedPenaltyScorer as nativeFixedPenaltyScorerImport;
403 pub(crate) type nativeFixedPenaltyScorer = nativeFixedPenaltyScorerImport;
404
405 /// [`Score`] implementation that uses a fixed penalty.
406 #[must_use]
407 #[repr(C)]
408 pub struct FixedPenaltyScorer {
409         /// A pointer to the opaque Rust object.
410
411         /// Nearly everywhere, inner must be non-null, however in places where
412         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
413         pub inner: *mut nativeFixedPenaltyScorer,
414         /// Indicates that this is the only struct which contains the same pointer.
415
416         /// Rust functions which take ownership of an object provided via an argument require
417         /// this to be true and invalidate the object pointed to by inner.
418         pub is_owned: bool,
419 }
420
421 impl Drop for FixedPenaltyScorer {
422         fn drop(&mut self) {
423                 if self.is_owned && !<*mut nativeFixedPenaltyScorer>::is_null(self.inner) {
424                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
425                 }
426         }
427 }
428 /// Frees any resources used by the FixedPenaltyScorer, if is_owned is set and inner is non-NULL.
429 #[no_mangle]
430 pub extern "C" fn FixedPenaltyScorer_free(this_obj: FixedPenaltyScorer) { }
431 #[allow(unused)]
432 /// Used only if an object of this type is returned as a trait impl by a method
433 pub(crate) extern "C" fn FixedPenaltyScorer_free_void(this_ptr: *mut c_void) {
434         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeFixedPenaltyScorer); }
435 }
436 #[allow(unused)]
437 impl FixedPenaltyScorer {
438         pub(crate) fn get_native_ref(&self) -> &'static nativeFixedPenaltyScorer {
439                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
440         }
441         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFixedPenaltyScorer {
442                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
443         }
444         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
445         pub(crate) fn take_inner(mut self) -> *mut nativeFixedPenaltyScorer {
446                 assert!(self.is_owned);
447                 let ret = ObjOps::untweak_ptr(self.inner);
448                 self.inner = core::ptr::null_mut();
449                 ret
450         }
451 }
452 impl Clone for FixedPenaltyScorer {
453         fn clone(&self) -> Self {
454                 Self {
455                         inner: if <*mut nativeFixedPenaltyScorer>::is_null(self.inner) { core::ptr::null_mut() } else {
456                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
457                         is_owned: true,
458                 }
459         }
460 }
461 #[allow(unused)]
462 /// Used only if an object of this type is returned as a trait impl by a method
463 pub(crate) extern "C" fn FixedPenaltyScorer_clone_void(this_ptr: *const c_void) -> *mut c_void {
464         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFixedPenaltyScorer)).clone() })) as *mut c_void
465 }
466 #[no_mangle]
467 /// Creates a copy of the FixedPenaltyScorer
468 pub extern "C" fn FixedPenaltyScorer_clone(orig: &FixedPenaltyScorer) -> FixedPenaltyScorer {
469         orig.clone()
470 }
471 /// Creates a new scorer using `penalty_msat`.
472 #[must_use]
473 #[no_mangle]
474 pub extern "C" fn FixedPenaltyScorer_with_penalty(mut penalty_msat: u64) -> crate::lightning::routing::scoring::FixedPenaltyScorer {
475         let mut ret = lightning::routing::scoring::FixedPenaltyScorer::with_penalty(penalty_msat);
476         crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
477 }
478
479 impl From<nativeFixedPenaltyScorer> for crate::lightning::routing::scoring::Score {
480         fn from(obj: nativeFixedPenaltyScorer) -> Self {
481                 let mut rust_obj = FixedPenaltyScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
482                 let mut ret = FixedPenaltyScorer_as_Score(&rust_obj);
483                 // 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
484                 rust_obj.inner = core::ptr::null_mut();
485                 ret.free = Some(FixedPenaltyScorer_free_void);
486                 ret
487         }
488 }
489 /// Constructs a new Score which calls the relevant methods on this_arg.
490 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
491 #[no_mangle]
492 pub extern "C" fn FixedPenaltyScorer_as_Score(this_arg: &FixedPenaltyScorer) -> crate::lightning::routing::scoring::Score {
493         crate::lightning::routing::scoring::Score {
494                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
495                 free: None,
496                 channel_penalty_msat: FixedPenaltyScorer_Score_channel_penalty_msat,
497                 payment_path_failed: FixedPenaltyScorer_Score_payment_path_failed,
498                 payment_path_successful: FixedPenaltyScorer_Score_payment_path_successful,
499                 probe_failed: FixedPenaltyScorer_Score_probe_failed,
500                 probe_successful: FixedPenaltyScorer_Score_probe_successful,
501                 write: FixedPenaltyScorer_write_void,
502         }
503 }
504
505 #[must_use]
506 extern "C" fn FixedPenaltyScorer_Score_channel_penalty_msat(this_arg: *const c_void, unused_0: u64, unused_1: &crate::lightning::routing::gossip::NodeId, unused_2: &crate::lightning::routing::gossip::NodeId, unused_3: crate::lightning::routing::scoring::ChannelUsage) -> u64 {
507         let mut ret = <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, unused_0, unused_1.get_native_ref(), unused_2.get_native_ref(), *unsafe { Box::from_raw(unused_3.take_inner()) });
508         ret
509 }
510 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) {
511         let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
512         <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..], _short_channel_id)
513 }
514 extern "C" fn FixedPenaltyScorer_Score_payment_path_successful(this_arg: *mut c_void, mut _path: crate::c_types::derived::CVec_RouteHopZ) {
515         let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
516         <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..])
517 }
518 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) {
519         let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
520         <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..], _short_channel_id)
521 }
522 extern "C" fn FixedPenaltyScorer_Score_probe_successful(this_arg: *mut c_void, mut _path: crate::c_types::derived::CVec_RouteHopZ) {
523         let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
524         <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..])
525 }
526
527 #[no_mangle]
528 /// Serialize the FixedPenaltyScorer object into a byte array which can be read by FixedPenaltyScorer_read
529 pub extern "C" fn FixedPenaltyScorer_write(obj: &crate::lightning::routing::scoring::FixedPenaltyScorer) -> crate::c_types::derived::CVec_u8Z {
530         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
531 }
532 #[no_mangle]
533 pub(crate) extern "C" fn FixedPenaltyScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
534         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFixedPenaltyScorer) })
535 }
536 #[no_mangle]
537 /// Read a FixedPenaltyScorer from a byte array, created by FixedPenaltyScorer_write
538 pub extern "C" fn FixedPenaltyScorer_read(ser: crate::c_types::u8slice, arg: u64) -> crate::c_types::derived::CResult_FixedPenaltyScorerDecodeErrorZ {
539         let arg_conv = arg;
540         let res: Result<lightning::routing::scoring::FixedPenaltyScorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
541         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() };
542         local_res
543 }
544
545 use lightning::routing::scoring::ProbabilisticScorer as nativeProbabilisticScorerImport;
546 pub(crate) type nativeProbabilisticScorer = nativeProbabilisticScorerImport<&'static lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger>;
547
548 /// [`Score`] implementation using channel success probability distributions.
549 ///
550 /// Based on *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
551 /// and Stefan Richter [[1]]. Given the uncertainty of channel liquidity balances, probability
552 /// distributions are defined based on knowledge learned from successful and unsuccessful attempts.
553 /// Then the negative `log10` of the success probability is used to determine the cost of routing a
554 /// specific HTLC amount through a channel.
555 ///
556 /// Knowledge about channel liquidity balances takes the form of upper and lower bounds on the
557 /// possible liquidity. Certainty of the bounds is decreased over time using a decay function. See
558 /// [`ProbabilisticScoringParameters`] for details.
559 ///
560 /// Since the scorer aims to learn the current channel liquidity balances, it works best for nodes
561 /// with high payment volume or that actively probe the [`NetworkGraph`]. Nodes with low payment
562 /// volume are more likely to experience failed payment paths, which would need to be retried.
563 ///
564 /// # Note
565 ///
566 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
567 /// behavior.
568 ///
569 /// [1]: https://arxiv.org/abs/2107.05322
570 #[must_use]
571 #[repr(C)]
572 pub struct ProbabilisticScorer {
573         /// A pointer to the opaque Rust object.
574
575         /// Nearly everywhere, inner must be non-null, however in places where
576         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
577         pub inner: *mut nativeProbabilisticScorer,
578         /// Indicates that this is the only struct which contains the same pointer.
579
580         /// Rust functions which take ownership of an object provided via an argument require
581         /// this to be true and invalidate the object pointed to by inner.
582         pub is_owned: bool,
583 }
584
585 impl Drop for ProbabilisticScorer {
586         fn drop(&mut self) {
587                 if self.is_owned && !<*mut nativeProbabilisticScorer>::is_null(self.inner) {
588                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
589                 }
590         }
591 }
592 /// Frees any resources used by the ProbabilisticScorer, if is_owned is set and inner is non-NULL.
593 #[no_mangle]
594 pub extern "C" fn ProbabilisticScorer_free(this_obj: ProbabilisticScorer) { }
595 #[allow(unused)]
596 /// Used only if an object of this type is returned as a trait impl by a method
597 pub(crate) extern "C" fn ProbabilisticScorer_free_void(this_ptr: *mut c_void) {
598         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScorer); }
599 }
600 #[allow(unused)]
601 impl ProbabilisticScorer {
602         pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScorer {
603                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
604         }
605         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScorer {
606                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
607         }
608         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
609         pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScorer {
610                 assert!(self.is_owned);
611                 let ret = ObjOps::untweak_ptr(self.inner);
612                 self.inner = core::ptr::null_mut();
613                 ret
614         }
615 }
616
617 use lightning::routing::scoring::ProbabilisticScoringParameters as nativeProbabilisticScoringParametersImport;
618 pub(crate) type nativeProbabilisticScoringParameters = nativeProbabilisticScoringParametersImport;
619
620 /// Parameters for configuring [`ProbabilisticScorer`].
621 ///
622 /// Used to configure base, liquidity, and amount penalties, the sum of which comprises the channel
623 /// penalty (i.e., the amount in msats willing to be paid to avoid routing through the channel).
624 ///
625 /// The penalty applied to any channel by the [`ProbabilisticScorer`] is the sum of each of the
626 /// parameters here.
627 #[must_use]
628 #[repr(C)]
629 pub struct ProbabilisticScoringParameters {
630         /// A pointer to the opaque Rust object.
631
632         /// Nearly everywhere, inner must be non-null, however in places where
633         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
634         pub inner: *mut nativeProbabilisticScoringParameters,
635         /// Indicates that this is the only struct which contains the same pointer.
636
637         /// Rust functions which take ownership of an object provided via an argument require
638         /// this to be true and invalidate the object pointed to by inner.
639         pub is_owned: bool,
640 }
641
642 impl Drop for ProbabilisticScoringParameters {
643         fn drop(&mut self) {
644                 if self.is_owned && !<*mut nativeProbabilisticScoringParameters>::is_null(self.inner) {
645                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
646                 }
647         }
648 }
649 /// Frees any resources used by the ProbabilisticScoringParameters, if is_owned is set and inner is non-NULL.
650 #[no_mangle]
651 pub extern "C" fn ProbabilisticScoringParameters_free(this_obj: ProbabilisticScoringParameters) { }
652 #[allow(unused)]
653 /// Used only if an object of this type is returned as a trait impl by a method
654 pub(crate) extern "C" fn ProbabilisticScoringParameters_free_void(this_ptr: *mut c_void) {
655         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScoringParameters); }
656 }
657 #[allow(unused)]
658 impl ProbabilisticScoringParameters {
659         pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringParameters {
660                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
661         }
662         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringParameters {
663                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
664         }
665         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
666         pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringParameters {
667                 assert!(self.is_owned);
668                 let ret = ObjOps::untweak_ptr(self.inner);
669                 self.inner = core::ptr::null_mut();
670                 ret
671         }
672 }
673 /// A fixed penalty in msats to apply to each channel.
674 ///
675 /// Default value: 500 msat
676 #[no_mangle]
677 pub extern "C" fn ProbabilisticScoringParameters_get_base_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
678         let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
679         *inner_val
680 }
681 /// A fixed penalty in msats to apply to each channel.
682 ///
683 /// Default value: 500 msat
684 #[no_mangle]
685 pub extern "C" fn ProbabilisticScoringParameters_set_base_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
686         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
687 }
688 /// A multiplier used with the payment amount to calculate a fixed penalty applied to each
689 /// channel, in excess of the [`base_penalty_msat`].
690 ///
691 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
692 /// fees plus penalty) for large payments. The penalty is computed as the product of this
693 /// multiplier and `2^30`ths of the payment amount.
694 ///
695 /// ie `base_penalty_amount_multiplier_msat * amount_msat / 2^30`
696 ///
697 /// Default value: 8,192 msat
698 ///
699 /// [`base_penalty_msat`]: Self::base_penalty_msat
700 #[no_mangle]
701 pub extern "C" fn ProbabilisticScoringParameters_get_base_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
702         let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_amount_multiplier_msat;
703         *inner_val
704 }
705 /// A multiplier used with the payment amount to calculate a fixed penalty applied to each
706 /// channel, in excess of the [`base_penalty_msat`].
707 ///
708 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
709 /// fees plus penalty) for large payments. The penalty is computed as the product of this
710 /// multiplier and `2^30`ths of the payment amount.
711 ///
712 /// ie `base_penalty_amount_multiplier_msat * amount_msat / 2^30`
713 ///
714 /// Default value: 8,192 msat
715 ///
716 /// [`base_penalty_msat`]: Self::base_penalty_msat
717 #[no_mangle]
718 pub extern "C" fn ProbabilisticScoringParameters_set_base_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
719         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_amount_multiplier_msat = val;
720 }
721 /// A multiplier used in conjunction with the negative `log10` of the channel's success
722 /// probability for a payment to determine the liquidity penalty.
723 ///
724 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
725 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
726 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
727 /// lower bounding the success probability to `0.01`) when the amount falls within the
728 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
729 /// result in a `u64::max_value` penalty, however.
730 ///
731 /// Default value: 40,000 msat
732 ///
733 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
734 #[no_mangle]
735 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
736         let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_multiplier_msat;
737         *inner_val
738 }
739 /// A multiplier used in conjunction with the negative `log10` of the channel's success
740 /// probability for a payment to determine the liquidity penalty.
741 ///
742 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
743 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
744 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
745 /// lower bounding the success probability to `0.01`) when the amount falls within the
746 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
747 /// result in a `u64::max_value` penalty, however.
748 ///
749 /// Default value: 40,000 msat
750 ///
751 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
752 #[no_mangle]
753 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
754         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_multiplier_msat = val;
755 }
756 /// The time required to elapse before any knowledge learned about channel liquidity balances is
757 /// cut in half.
758 ///
759 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
760 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
761 /// the certainty of the channel liquidity balance.
762 ///
763 /// Default value: 1 hour
764 ///
765 /// # Note
766 ///
767 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
768 /// liquidity knowledge will never decay except when the bounds cross.
769 #[no_mangle]
770 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_offset_half_life(this_ptr: &ProbabilisticScoringParameters) -> u64 {
771         let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_offset_half_life;
772         inner_val.as_secs()
773 }
774 /// The time required to elapse before any knowledge learned about channel liquidity balances is
775 /// cut in half.
776 ///
777 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
778 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
779 /// the certainty of the channel liquidity balance.
780 ///
781 /// Default value: 1 hour
782 ///
783 /// # Note
784 ///
785 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
786 /// liquidity knowledge will never decay except when the bounds cross.
787 #[no_mangle]
788 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_offset_half_life(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
789         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_offset_half_life = core::time::Duration::from_secs(val);
790 }
791 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
792 /// channel's success probability for the payment to determine the amount penalty.
793 ///
794 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
795 /// fees plus penalty) for large payments. The penalty is computed as the product of this
796 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
797 /// success probability.
798 ///
799 /// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
800 ///
801 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
802 /// the amount will result in a penalty of the multiplier. And, as the success probability
803 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
804 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
805 /// fall below `1`.
806 ///
807 /// Default value: 256 msat
808 #[no_mangle]
809 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
810         let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_amount_multiplier_msat;
811         *inner_val
812 }
813 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
814 /// channel's success probability for the payment to determine the amount penalty.
815 ///
816 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
817 /// fees plus penalty) for large payments. The penalty is computed as the product of this
818 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
819 /// success probability.
820 ///
821 /// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
822 ///
823 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
824 /// the amount will result in a penalty of the multiplier. And, as the success probability
825 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
826 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
827 /// fall below `1`.
828 ///
829 /// Default value: 256 msat
830 #[no_mangle]
831 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
832         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_amount_multiplier_msat = val;
833 }
834 /// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
835 /// channel's capacity, which makes us prefer nodes with a smaller `htlc_maximum_msat`. We
836 /// treat such nodes preferentially as this makes balance discovery attacks harder to execute,
837 /// thereby creating an incentive to restrict `htlc_maximum_msat` and improve privacy.
838 ///
839 /// Default value: 250 msat
840 #[no_mangle]
841 pub extern "C" fn ProbabilisticScoringParameters_get_anti_probing_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
842         let mut inner_val = &mut this_ptr.get_native_mut_ref().anti_probing_penalty_msat;
843         *inner_val
844 }
845 /// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
846 /// channel's capacity, which makes us prefer nodes with a smaller `htlc_maximum_msat`. We
847 /// treat such nodes preferentially as this makes balance discovery attacks harder to execute,
848 /// thereby creating an incentive to restrict `htlc_maximum_msat` and improve privacy.
849 ///
850 /// Default value: 250 msat
851 #[no_mangle]
852 pub extern "C" fn ProbabilisticScoringParameters_set_anti_probing_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
853         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.anti_probing_penalty_msat = val;
854 }
855 /// This penalty is applied when the amount we're attempting to send over a channel exceeds our
856 /// current estimate of the channel's available liquidity.
857 ///
858 /// Note that in this case all other penalties, including the
859 /// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
860 /// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
861 /// applicable, are still included in the overall penalty.
862 ///
863 /// If you wish to avoid creating paths with such channels entirely, setting this to a value of
864 /// `u64::max_value()` will guarantee that.
865 ///
866 /// Default value: 1_0000_0000_000 msat (1 Bitcoin)
867 ///
868 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
869 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
870 /// [`base_penalty_msat`]: Self::base_penalty_msat
871 /// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
872 #[no_mangle]
873 pub extern "C" fn ProbabilisticScoringParameters_get_considered_impossible_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
874         let mut inner_val = &mut this_ptr.get_native_mut_ref().considered_impossible_penalty_msat;
875         *inner_val
876 }
877 /// This penalty is applied when the amount we're attempting to send over a channel exceeds our
878 /// current estimate of the channel's available liquidity.
879 ///
880 /// Note that in this case all other penalties, including the
881 /// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
882 /// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
883 /// applicable, are still included in the overall penalty.
884 ///
885 /// If you wish to avoid creating paths with such channels entirely, setting this to a value of
886 /// `u64::max_value()` will guarantee that.
887 ///
888 /// Default value: 1_0000_0000_000 msat (1 Bitcoin)
889 ///
890 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
891 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
892 /// [`base_penalty_msat`]: Self::base_penalty_msat
893 /// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
894 #[no_mangle]
895 pub extern "C" fn ProbabilisticScoringParameters_set_considered_impossible_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
896         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.considered_impossible_penalty_msat = val;
897 }
898 impl Clone for ProbabilisticScoringParameters {
899         fn clone(&self) -> Self {
900                 Self {
901                         inner: if <*mut nativeProbabilisticScoringParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
902                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
903                         is_owned: true,
904                 }
905         }
906 }
907 #[allow(unused)]
908 /// Used only if an object of this type is returned as a trait impl by a method
909 pub(crate) extern "C" fn ProbabilisticScoringParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
910         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeProbabilisticScoringParameters)).clone() })) as *mut c_void
911 }
912 #[no_mangle]
913 /// Creates a copy of the ProbabilisticScoringParameters
914 pub extern "C" fn ProbabilisticScoringParameters_clone(orig: &ProbabilisticScoringParameters) -> ProbabilisticScoringParameters {
915         orig.clone()
916 }
917 /// Creates a new scorer using the given scoring parameters for sending payments from a node
918 /// through a network graph.
919 #[must_use]
920 #[no_mangle]
921 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 {
922         let mut ret = lightning::routing::scoring::ProbabilisticScorer::new(*unsafe { Box::from_raw(params.take_inner()) }, network_graph.get_native_ref(), logger);
923         crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
924 }
925
926 /// Dump the contents of this scorer into the configured logger.
927 ///
928 /// Note that this writes roughly one line per channel for which we have a liquidity estimate,
929 /// which may be a substantial amount of log output.
930 #[no_mangle]
931 pub extern "C" fn ProbabilisticScorer_debug_log_liquidity_stats(this_arg: &crate::lightning::routing::scoring::ProbabilisticScorer) {
932         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.debug_log_liquidity_stats()
933 }
934
935 /// Query the estimated minimum and maximum liquidity available for sending a payment over the
936 /// channel with `scid` towards the given `target` node.
937 #[must_use]
938 #[no_mangle]
939 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 {
940         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.estimated_channel_liquidity_range(scid, target.get_native_ref());
941         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 }) };
942         local_ret
943 }
944
945 /// Marks the node with the given `node_id` as banned, i.e.,
946 /// it will be avoided during path finding.
947 #[no_mangle]
948 pub extern "C" fn ProbabilisticScorer_add_banned(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer, node_id: &crate::lightning::routing::gossip::NodeId) {
949         unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.add_banned(node_id.get_native_ref())
950 }
951
952 /// Removes the node with the given `node_id` from the list of nodes to avoid.
953 #[no_mangle]
954 pub extern "C" fn ProbabilisticScorer_remove_banned(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer, node_id: &crate::lightning::routing::gossip::NodeId) {
955         unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.remove_banned(node_id.get_native_ref())
956 }
957
958 /// Sets a manual penalty for the given node.
959 #[no_mangle]
960 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) {
961         unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.set_manual_penalty(node_id.get_native_ref(), penalty)
962 }
963
964 /// Removes the node with the given `node_id` from the list of manual penalties.
965 #[no_mangle]
966 pub extern "C" fn ProbabilisticScorer_remove_manual_penalty(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer, node_id: &crate::lightning::routing::gossip::NodeId) {
967         unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.remove_manual_penalty(node_id.get_native_ref())
968 }
969
970 /// Clears the list of manual penalties that are applied during path finding.
971 #[no_mangle]
972 pub extern "C" fn ProbabilisticScorer_clear_manual_penalties(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer) {
973         unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.clear_manual_penalties()
974 }
975
976 /// Marks all nodes in the given list as banned, i.e.,
977 /// they will be avoided during path finding.
978 #[no_mangle]
979 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) {
980         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()) } }); };
981         unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringParameters)) }.add_banned_from_list(local_node_ids)
982 }
983
984 /// Creates a "default" ProbabilisticScoringParameters. See struct and individual field documentaiton for details on which values are used.
985 #[must_use]
986 #[no_mangle]
987 pub extern "C" fn ProbabilisticScoringParameters_default() -> ProbabilisticScoringParameters {
988         ProbabilisticScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
989 }
990 impl From<nativeProbabilisticScorer> for crate::lightning::routing::scoring::Score {
991         fn from(obj: nativeProbabilisticScorer) -> Self {
992                 let mut rust_obj = ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
993                 let mut ret = ProbabilisticScorer_as_Score(&rust_obj);
994                 // 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
995                 rust_obj.inner = core::ptr::null_mut();
996                 ret.free = Some(ProbabilisticScorer_free_void);
997                 ret
998         }
999 }
1000 /// Constructs a new Score which calls the relevant methods on this_arg.
1001 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
1002 #[no_mangle]
1003 pub extern "C" fn ProbabilisticScorer_as_Score(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::Score {
1004         crate::lightning::routing::scoring::Score {
1005                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1006                 free: None,
1007                 channel_penalty_msat: ProbabilisticScorer_Score_channel_penalty_msat,
1008                 payment_path_failed: ProbabilisticScorer_Score_payment_path_failed,
1009                 payment_path_successful: ProbabilisticScorer_Score_payment_path_successful,
1010                 probe_failed: ProbabilisticScorer_Score_probe_failed,
1011                 probe_successful: ProbabilisticScorer_Score_probe_successful,
1012                 write: ProbabilisticScorer_write_void,
1013         }
1014 }
1015
1016 #[must_use]
1017 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 {
1018         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()) });
1019         ret
1020 }
1021 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) {
1022         let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1023         <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..], short_channel_id)
1024 }
1025 extern "C" fn ProbabilisticScorer_Score_payment_path_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
1026         let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1027         <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..])
1028 }
1029 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) {
1030         let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1031         <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..], short_channel_id)
1032 }
1033 extern "C" fn ProbabilisticScorer_Score_probe_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
1034         let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1035         <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..])
1036 }
1037
1038 mod approx {
1039
1040 use alloc::str::FromStr;
1041 use core::ffi::c_void;
1042 use core::convert::Infallible;
1043 use bitcoin::hashes::Hash;
1044 use crate::c_types::*;
1045 #[cfg(feature="no-std")]
1046 use alloc::{vec::Vec, boxed::Box};
1047
1048 }
1049 #[no_mangle]
1050 /// Serialize the ProbabilisticScorer object into a byte array which can be read by ProbabilisticScorer_read
1051 pub extern "C" fn ProbabilisticScorer_write(obj: &crate::lightning::routing::scoring::ProbabilisticScorer) -> crate::c_types::derived::CVec_u8Z {
1052         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
1053 }
1054 #[no_mangle]
1055 pub(crate) extern "C" fn ProbabilisticScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
1056         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeProbabilisticScorer) })
1057 }
1058 #[no_mangle]
1059 /// Read a ProbabilisticScorer from a byte array, created by ProbabilisticScorer_write
1060 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 {
1061         let arg_a_conv = *unsafe { Box::from_raw(arg_a.take_inner()) };
1062         let arg_b_conv = arg_b.get_native_ref();
1063         let arg_c_conv = arg_c;
1064         let arg_conv = (arg_a_conv, arg_b_conv, arg_c_conv);
1065         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);
1066         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() };
1067         local_res
1068 }