bc3af0acfedf6141edabe966274d99a4e5b77735
[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 //! [`Scorer`] may be given to [`find_route`] to score payment channels during path finding when a
12 //! 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::{Scorer, ScoringParameters};
22 //! # use lightning::util::logger::{Logger, Record};
23 //! # use secp256k1::key::PublicKey;
24 //! #
25 //! # struct FakeLogger {};
26 //! # impl Logger for FakeLogger {
27 //! #     fn log(&self, record: &Record) { unimplemented!() }
28 //! # }
29 //! # fn find_scored_route(payer: PublicKey, params: RouteParameters, network_graph: NetworkGraph) {
30 //! # let logger = FakeLogger {};
31 //! #
32 //! // Use the default channel penalties.
33 //! let scorer = Scorer::default();
34 //!
35 //! // Or use custom channel penalties.
36 //! let scorer = Scorer::new(ScoringParameters {
37 //!     base_penalty_msat: 1000,
38 //!     failure_penalty_msat: 2 * 1024 * 1000,
39 //!     ..ScoringParameters::default()
40 //! });
41 //!
42 //! let route = find_route(&payer, &params, &network_graph, None, &logger, &scorer);
43 //! # }
44 //! ```
45 //!
46 //! # Note
47 //!
48 //! Persisting when built with feature `no-std` and restoring without it, or vice versa, uses
49 //! different types and thus is undefined.
50 //!
51 //! [`find_route`]: crate::routing::router::find_route
52
53 use std::str::FromStr;
54 use std::ffi::c_void;
55 use core::convert::Infallible;
56 use bitcoin::hashes::Hash;
57 use crate::c_types::*;
58
59 /// An interface used to score payment channels for path finding.
60 ///
61 ///\tScoring is in terms of fees willing to be paid in order to avoid routing through a channel.
62 #[repr(C)]
63 pub struct Score {
64         /// An opaque pointer which is passed to your function implementations as an argument.
65         /// This has no meaning in the LDK, and can be NULL or any other value.
66         pub this_arg: *mut c_void,
67         /// Returns the fee in msats willing to be paid to avoid routing `send_amt_msat` through the
68         /// given channel in the direction from `source` to `target`.
69         ///
70         /// The channel's capacity (less any other MPP parts which are also being considered for use in
71         /// the same payment) is given by `channel_capacity_msat`. It may be guessed from various
72         /// sources or assumed from no data at all.
73         ///
74         /// For hints provided in the invoice, we assume the channel has sufficient capacity to accept
75         /// the invoice's full amount, and provide a `channel_capacity_msat` of `None`. In all other
76         /// cases it is set to `Some`, even if we're guessing at the channel value.
77         ///
78         /// Your code should be overflow-safe through a `channel_capacity_msat` of 21 million BTC.
79         #[must_use]
80         pub channel_penalty_msat: extern "C" fn (this_arg: *const c_void, short_channel_id: u64, send_amt_msat: u64, channel_capacity_msat: crate::c_types::derived::COption_u64Z, source: &crate::lightning::routing::network_graph::NodeId, target: &crate::lightning::routing::network_graph::NodeId) -> u64,
81         /// Handles updating channel penalties after failing to route through a channel.
82         pub payment_path_failed: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ, short_channel_id: u64),
83         /// Handles updating channel penalties after successfully routing along a path.
84         pub payment_path_successful: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ),
85         /// Serialize the object into a byte array
86         pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
87         /// Frees any resources associated with this object given its this_arg pointer.
88         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
89         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
90 }
91 unsafe impl Send for Score {}
92 unsafe impl Sync for Score {}
93 #[no_mangle]
94 pub(crate) extern "C" fn Score_clone_fields(orig: &Score) -> Score {
95         Score {
96                 this_arg: orig.this_arg,
97                 channel_penalty_msat: Clone::clone(&orig.channel_penalty_msat),
98                 payment_path_failed: Clone::clone(&orig.payment_path_failed),
99                 payment_path_successful: Clone::clone(&orig.payment_path_successful),
100                 write: Clone::clone(&orig.write),
101                 free: Clone::clone(&orig.free),
102         }
103 }
104 impl lightning::util::ser::Writeable for Score {
105         fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
106                 let vec = (self.write)(self.this_arg);
107                 w.write_all(vec.as_slice())
108         }
109 }
110
111 use lightning::routing::scoring::Score as rustScore;
112 impl rustScore for Score {
113         fn channel_penalty_msat(&self, mut short_channel_id: u64, mut send_amt_msat: u64, mut channel_capacity_msat: Option<u64>, mut source: &lightning::routing::network_graph::NodeId, mut target: &lightning::routing::network_graph::NodeId) -> u64 {
114                 let mut local_channel_capacity_msat = if channel_capacity_msat.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { channel_capacity_msat.unwrap() }) };
115                 let mut ret = (self.channel_penalty_msat)(self.this_arg, short_channel_id, send_amt_msat, local_channel_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 std::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 std::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 = std::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) -> MultiThreadedLockableScore {
259         let mut ret = lightning::routing::scoring::MultiThreadedLockableScore::new(score);
260         MultiThreadedLockableScore { inner: ObjOps::heap_alloc(ret), is_owned: true }
261 }
262
263
264 use lightning::routing::scoring::Scorer as nativeScorerImport;
265 pub(crate) type nativeScorer = nativeScorerImport;
266
267 /// [`Score`] implementation that provides reasonable default behavior.
268 ///
269 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
270 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
271 ///
272 /// See [module-level documentation] for usage.
273 ///
274 /// [module-level documentation]: crate::routing::scoring
275 #[must_use]
276 #[repr(C)]
277 pub struct Scorer {
278         /// A pointer to the opaque Rust object.
279
280         /// Nearly everywhere, inner must be non-null, however in places where
281         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
282         pub inner: *mut nativeScorer,
283         /// Indicates that this is the only struct which contains the same pointer.
284
285         /// Rust functions which take ownership of an object provided via an argument require
286         /// this to be true and invalidate the object pointed to by inner.
287         pub is_owned: bool,
288 }
289
290 impl Drop for Scorer {
291         fn drop(&mut self) {
292                 if self.is_owned && !<*mut nativeScorer>::is_null(self.inner) {
293                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
294                 }
295         }
296 }
297 /// Frees any resources used by the Scorer, if is_owned is set and inner is non-NULL.
298 #[no_mangle]
299 pub extern "C" fn Scorer_free(this_obj: Scorer) { }
300 #[allow(unused)]
301 /// Used only if an object of this type is returned as a trait impl by a method
302 pub(crate) extern "C" fn Scorer_free_void(this_ptr: *mut c_void) {
303         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeScorer); }
304 }
305 #[allow(unused)]
306 impl Scorer {
307         pub(crate) fn get_native_ref(&self) -> &'static nativeScorer {
308                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
309         }
310         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeScorer {
311                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
312         }
313         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
314         pub(crate) fn take_inner(mut self) -> *mut nativeScorer {
315                 assert!(self.is_owned);
316                 let ret = ObjOps::untweak_ptr(self.inner);
317                 self.inner = std::ptr::null_mut();
318                 ret
319         }
320 }
321
322 use lightning::routing::scoring::ScoringParameters as nativeScoringParametersImport;
323 pub(crate) type nativeScoringParameters = nativeScoringParametersImport;
324
325 /// Parameters for configuring [`Scorer`].
326 #[must_use]
327 #[repr(C)]
328 pub struct ScoringParameters {
329         /// A pointer to the opaque Rust object.
330
331         /// Nearly everywhere, inner must be non-null, however in places where
332         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
333         pub inner: *mut nativeScoringParameters,
334         /// Indicates that this is the only struct which contains the same pointer.
335
336         /// Rust functions which take ownership of an object provided via an argument require
337         /// this to be true and invalidate the object pointed to by inner.
338         pub is_owned: bool,
339 }
340
341 impl Drop for ScoringParameters {
342         fn drop(&mut self) {
343                 if self.is_owned && !<*mut nativeScoringParameters>::is_null(self.inner) {
344                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
345                 }
346         }
347 }
348 /// Frees any resources used by the ScoringParameters, if is_owned is set and inner is non-NULL.
349 #[no_mangle]
350 pub extern "C" fn ScoringParameters_free(this_obj: ScoringParameters) { }
351 #[allow(unused)]
352 /// Used only if an object of this type is returned as a trait impl by a method
353 pub(crate) extern "C" fn ScoringParameters_free_void(this_ptr: *mut c_void) {
354         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeScoringParameters); }
355 }
356 #[allow(unused)]
357 impl ScoringParameters {
358         pub(crate) fn get_native_ref(&self) -> &'static nativeScoringParameters {
359                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
360         }
361         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeScoringParameters {
362                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
363         }
364         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
365         pub(crate) fn take_inner(mut self) -> *mut nativeScoringParameters {
366                 assert!(self.is_owned);
367                 let ret = ObjOps::untweak_ptr(self.inner);
368                 self.inner = std::ptr::null_mut();
369                 ret
370         }
371 }
372 /// A fixed penalty in msats to apply to each channel.
373 ///
374 /// Default value: 500 msat
375 #[no_mangle]
376 pub extern "C" fn ScoringParameters_get_base_penalty_msat(this_ptr: &ScoringParameters) -> u64 {
377         let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
378         *inner_val
379 }
380 /// A fixed penalty in msats to apply to each channel.
381 ///
382 /// Default value: 500 msat
383 #[no_mangle]
384 pub extern "C" fn ScoringParameters_set_base_penalty_msat(this_ptr: &mut ScoringParameters, mut val: u64) {
385         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
386 }
387 /// A penalty in msats to apply to a channel upon failing to relay a payment.
388 ///
389 /// This accumulates for each failure but may be reduced over time based on
390 /// [`failure_penalty_half_life`] or when successfully routing through a channel.
391 ///
392 /// Default value: 1,024,000 msat
393 ///
394 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
395 #[no_mangle]
396 pub extern "C" fn ScoringParameters_get_failure_penalty_msat(this_ptr: &ScoringParameters) -> u64 {
397         let mut inner_val = &mut this_ptr.get_native_mut_ref().failure_penalty_msat;
398         *inner_val
399 }
400 /// A penalty in msats to apply to a channel upon failing to relay a payment.
401 ///
402 /// This accumulates for each failure but may be reduced over time based on
403 /// [`failure_penalty_half_life`] or when successfully routing through a channel.
404 ///
405 /// Default value: 1,024,000 msat
406 ///
407 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
408 #[no_mangle]
409 pub extern "C" fn ScoringParameters_set_failure_penalty_msat(this_ptr: &mut ScoringParameters, mut val: u64) {
410         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure_penalty_msat = val;
411 }
412 /// When the amount being sent over a channel is this many 1024ths of the total channel
413 /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
414 ///
415 /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
416 ///
417 /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
418 #[no_mangle]
419 pub extern "C" fn ScoringParameters_get_overuse_penalty_start_1024th(this_ptr: &ScoringParameters) -> u16 {
420         let mut inner_val = &mut this_ptr.get_native_mut_ref().overuse_penalty_start_1024th;
421         *inner_val
422 }
423 /// When the amount being sent over a channel is this many 1024ths of the total channel
424 /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
425 ///
426 /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
427 ///
428 /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
429 #[no_mangle]
430 pub extern "C" fn ScoringParameters_set_overuse_penalty_start_1024th(this_ptr: &mut ScoringParameters, mut val: u16) {
431         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.overuse_penalty_start_1024th = val;
432 }
433 /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
434 /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
435 ///
436 /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
437 ///                to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
438 ///
439 /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
440 #[no_mangle]
441 pub extern "C" fn ScoringParameters_get_overuse_penalty_msat_per_1024th(this_ptr: &ScoringParameters) -> u64 {
442         let mut inner_val = &mut this_ptr.get_native_mut_ref().overuse_penalty_msat_per_1024th;
443         *inner_val
444 }
445 /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
446 /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
447 ///
448 /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
449 ///                to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
450 ///
451 /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
452 #[no_mangle]
453 pub extern "C" fn ScoringParameters_set_overuse_penalty_msat_per_1024th(this_ptr: &mut ScoringParameters, mut val: u64) {
454         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.overuse_penalty_msat_per_1024th = val;
455 }
456 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
457 /// cut in half.
458 ///
459 /// Successfully routing through a channel will immediately cut the penalty in half as well.
460 ///
461 /// # Note
462 ///
463 /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
464 /// never decay.
465 ///
466 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
467 #[no_mangle]
468 pub extern "C" fn ScoringParameters_get_failure_penalty_half_life(this_ptr: &ScoringParameters) -> u64 {
469         let mut inner_val = &mut this_ptr.get_native_mut_ref().failure_penalty_half_life;
470         inner_val.as_secs()
471 }
472 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
473 /// cut in half.
474 ///
475 /// Successfully routing through a channel will immediately cut the penalty in half as well.
476 ///
477 /// # Note
478 ///
479 /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
480 /// never decay.
481 ///
482 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
483 #[no_mangle]
484 pub extern "C" fn ScoringParameters_set_failure_penalty_half_life(this_ptr: &mut ScoringParameters, mut val: u64) {
485         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure_penalty_half_life = std::time::Duration::from_secs(val);
486 }
487 /// Constructs a new ScoringParameters given each field
488 #[must_use]
489 #[no_mangle]
490 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 {
491         ScoringParameters { inner: ObjOps::heap_alloc(nativeScoringParameters {
492                 base_penalty_msat: base_penalty_msat_arg,
493                 failure_penalty_msat: failure_penalty_msat_arg,
494                 overuse_penalty_start_1024th: overuse_penalty_start_1024th_arg,
495                 overuse_penalty_msat_per_1024th: overuse_penalty_msat_per_1024th_arg,
496                 failure_penalty_half_life: std::time::Duration::from_secs(failure_penalty_half_life_arg),
497         }), is_owned: true }
498 }
499 #[no_mangle]
500 /// Serialize the ScoringParameters object into a byte array which can be read by ScoringParameters_read
501 pub extern "C" fn ScoringParameters_write(obj: &ScoringParameters) -> crate::c_types::derived::CVec_u8Z {
502         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
503 }
504 #[no_mangle]
505 pub(crate) extern "C" fn ScoringParameters_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
506         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeScoringParameters) })
507 }
508 #[no_mangle]
509 /// Read a ScoringParameters from a byte array, created by ScoringParameters_write
510 pub extern "C" fn ScoringParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ScoringParametersDecodeErrorZ {
511         let res: Result<lightning::routing::scoring::ScoringParameters, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
512         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() };
513         local_res
514 }
515 /// Creates a new scorer using the given scoring parameters.
516 #[must_use]
517 #[no_mangle]
518 pub extern "C" fn Scorer_new(mut params: crate::lightning::routing::scoring::ScoringParameters) -> Scorer {
519         let mut ret = lightning::routing::scoring::Scorer::new(*unsafe { Box::from_raw(params.take_inner()) });
520         Scorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
521 }
522
523 /// Creates a "default" Scorer. See struct and individual field documentaiton for details on which values are used.
524 #[must_use]
525 #[no_mangle]
526 pub extern "C" fn Scorer_default() -> Scorer {
527         Scorer { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
528 }
529 /// Creates a "default" ScoringParameters. See struct and individual field documentaiton for details on which values are used.
530 #[must_use]
531 #[no_mangle]
532 pub extern "C" fn ScoringParameters_default() -> ScoringParameters {
533         ScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
534 }
535 impl From<nativeScorer> for crate::lightning::routing::scoring::Score {
536         fn from(obj: nativeScorer) -> Self {
537                 let mut rust_obj = Scorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
538                 let mut ret = Scorer_as_Score(&rust_obj);
539                 // 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
540                 rust_obj.inner = std::ptr::null_mut();
541                 ret.free = Some(Scorer_free_void);
542                 ret
543         }
544 }
545 /// Constructs a new Score which calls the relevant methods on this_arg.
546 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
547 #[no_mangle]
548 pub extern "C" fn Scorer_as_Score(this_arg: &Scorer) -> crate::lightning::routing::scoring::Score {
549         crate::lightning::routing::scoring::Score {
550                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
551                 free: None,
552                 channel_penalty_msat: Scorer_Score_channel_penalty_msat,
553                 payment_path_failed: Scorer_Score_payment_path_failed,
554                 payment_path_successful: Scorer_Score_payment_path_successful,
555                 write: Scorer_write_void,
556         }
557 }
558
559 #[must_use]
560 extern "C" fn Scorer_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, mut send_amt_msat: u64, mut chan_capacity_opt: crate::c_types::derived::COption_u64Z, _source: &crate::lightning::routing::network_graph::NodeId, _target: &crate::lightning::routing::network_graph::NodeId) -> u64 {
561         let mut local_chan_capacity_opt = if chan_capacity_opt.is_some() { Some( { chan_capacity_opt.take() }) } else { None };
562         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, local_chan_capacity_opt, _source.get_native_ref(), _target.get_native_ref());
563         ret
564 }
565 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) {
566         let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
567         <nativeScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeScorer) }, &local__path[..], short_channel_id)
568 }
569 extern "C" fn Scorer_Score_payment_path_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
570         let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
571         <nativeScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeScorer) }, &local_path[..])
572 }
573
574 #[no_mangle]
575 /// Serialize the Scorer object into a byte array which can be read by Scorer_read
576 pub extern "C" fn Scorer_write(obj: &Scorer) -> crate::c_types::derived::CVec_u8Z {
577         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
578 }
579 #[no_mangle]
580 pub(crate) extern "C" fn Scorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
581         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeScorer) })
582 }
583 #[no_mangle]
584 /// Read a Scorer from a byte array, created by Scorer_write
585 pub extern "C" fn Scorer_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ScorerDecodeErrorZ {
586         let res: Result<lightning::routing::scoring::Scorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
587         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() };
588         local_res
589 }
590 mod time {
591
592 use std::str::FromStr;
593 use std::ffi::c_void;
594 use core::convert::Infallible;
595 use bitcoin::hashes::Hash;
596 use crate::c_types::*;
597
598 }