Merge pull request #49 from TheBlueMatt/main
[ldk-c-bindings] / lightning-c-bindings / src / lightning / routing / scorer.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 [`routing::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::scorer::{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 //! If persisting [`Scorer`], it must be restored using the same [`Time`] parameterization. Using a
49 //! different type results in undefined behavior. Specifically, persisting when built with feature
50 //! `no-std` and restoring without it, or vice versa, uses different types and thus is undefined.
51 //!
52 //! [`find_route`]: crate::routing::router::find_route
53
54 use std::str::FromStr;
55 use std::ffi::c_void;
56 use core::convert::Infallible;
57 use bitcoin::hashes::Hash;
58 use crate::c_types::*;
59
60 mod sealed {
61
62 use std::str::FromStr;
63 use std::ffi::c_void;
64 use core::convert::Infallible;
65 use bitcoin::hashes::Hash;
66 use crate::c_types::*;
67
68 }
69
70 use lightning::routing::scorer::Scorer as nativeScorerImport;
71 pub(crate) type nativeScorer = nativeScorerImport;
72
73 /// [`routing::Score`] implementation that provides reasonable default behavior.
74 ///
75 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
76 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
77 ///
78 /// See [module-level documentation] for usage.
79 ///
80 /// [module-level documentation]: crate::routing::scorer
81 #[must_use]
82 #[repr(C)]
83 pub struct Scorer {
84         /// A pointer to the opaque Rust object.
85
86         /// Nearly everywhere, inner must be non-null, however in places where
87         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
88         pub inner: *mut nativeScorer,
89         /// Indicates that this is the only struct which contains the same pointer.
90
91         /// Rust functions which take ownership of an object provided via an argument require
92         /// this to be true and invalidate the object pointed to by inner.
93         pub is_owned: bool,
94 }
95
96 impl Drop for Scorer {
97         fn drop(&mut self) {
98                 if self.is_owned && !<*mut nativeScorer>::is_null(self.inner) {
99                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
100                 }
101         }
102 }
103 /// Frees any resources used by the Scorer, if is_owned is set and inner is non-NULL.
104 #[no_mangle]
105 pub extern "C" fn Scorer_free(this_obj: Scorer) { }
106 #[allow(unused)]
107 /// Used only if an object of this type is returned as a trait impl by a method
108 pub(crate) extern "C" fn Scorer_free_void(this_ptr: *mut c_void) {
109         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeScorer); }
110 }
111 #[allow(unused)]
112 impl Scorer {
113         pub(crate) fn get_native_ref(&self) -> &'static nativeScorer {
114                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
115         }
116         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeScorer {
117                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
118         }
119         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
120         pub(crate) fn take_inner(mut self) -> *mut nativeScorer {
121                 assert!(self.is_owned);
122                 let ret = ObjOps::untweak_ptr(self.inner);
123                 self.inner = std::ptr::null_mut();
124                 ret
125         }
126 }
127
128 use lightning::routing::scorer::ScoringParameters as nativeScoringParametersImport;
129 pub(crate) type nativeScoringParameters = nativeScoringParametersImport;
130
131 /// Parameters for configuring [`Scorer`].
132 #[must_use]
133 #[repr(C)]
134 pub struct ScoringParameters {
135         /// A pointer to the opaque Rust object.
136
137         /// Nearly everywhere, inner must be non-null, however in places where
138         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
139         pub inner: *mut nativeScoringParameters,
140         /// Indicates that this is the only struct which contains the same pointer.
141
142         /// Rust functions which take ownership of an object provided via an argument require
143         /// this to be true and invalidate the object pointed to by inner.
144         pub is_owned: bool,
145 }
146
147 impl Drop for ScoringParameters {
148         fn drop(&mut self) {
149                 if self.is_owned && !<*mut nativeScoringParameters>::is_null(self.inner) {
150                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
151                 }
152         }
153 }
154 /// Frees any resources used by the ScoringParameters, if is_owned is set and inner is non-NULL.
155 #[no_mangle]
156 pub extern "C" fn ScoringParameters_free(this_obj: ScoringParameters) { }
157 #[allow(unused)]
158 /// Used only if an object of this type is returned as a trait impl by a method
159 pub(crate) extern "C" fn ScoringParameters_free_void(this_ptr: *mut c_void) {
160         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeScoringParameters); }
161 }
162 #[allow(unused)]
163 impl ScoringParameters {
164         pub(crate) fn get_native_ref(&self) -> &'static nativeScoringParameters {
165                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
166         }
167         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeScoringParameters {
168                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
169         }
170         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
171         pub(crate) fn take_inner(mut self) -> *mut nativeScoringParameters {
172                 assert!(self.is_owned);
173                 let ret = ObjOps::untweak_ptr(self.inner);
174                 self.inner = std::ptr::null_mut();
175                 ret
176         }
177 }
178 /// A fixed penalty in msats to apply to each channel.
179 #[no_mangle]
180 pub extern "C" fn ScoringParameters_get_base_penalty_msat(this_ptr: &ScoringParameters) -> u64 {
181         let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
182         *inner_val
183 }
184 /// A fixed penalty in msats to apply to each channel.
185 #[no_mangle]
186 pub extern "C" fn ScoringParameters_set_base_penalty_msat(this_ptr: &mut ScoringParameters, mut val: u64) {
187         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
188 }
189 /// A penalty in msats to apply to a channel upon failing to relay a payment.
190 ///
191 /// This accumulates for each failure but may be reduced over time based on
192 /// [`failure_penalty_half_life`].
193 ///
194 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
195 #[no_mangle]
196 pub extern "C" fn ScoringParameters_get_failure_penalty_msat(this_ptr: &ScoringParameters) -> u64 {
197         let mut inner_val = &mut this_ptr.get_native_mut_ref().failure_penalty_msat;
198         *inner_val
199 }
200 /// A penalty in msats to apply to a channel upon failing to relay a payment.
201 ///
202 /// This accumulates for each failure but may be reduced over time based on
203 /// [`failure_penalty_half_life`].
204 ///
205 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
206 #[no_mangle]
207 pub extern "C" fn ScoringParameters_set_failure_penalty_msat(this_ptr: &mut ScoringParameters, mut val: u64) {
208         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure_penalty_msat = val;
209 }
210 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
211 /// cut in half.
212 ///
213 /// # Note
214 ///
215 /// When time is an [`Eternity`], as is default when enabling feature `no-std`, it will never
216 /// elapse. Therefore, this penalty will never decay.
217 ///
218 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
219 #[no_mangle]
220 pub extern "C" fn ScoringParameters_get_failure_penalty_half_life(this_ptr: &ScoringParameters) -> u64 {
221         let mut inner_val = &mut this_ptr.get_native_mut_ref().failure_penalty_half_life;
222         inner_val.as_secs()
223 }
224 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
225 /// cut in half.
226 ///
227 /// # Note
228 ///
229 /// When time is an [`Eternity`], as is default when enabling feature `no-std`, it will never
230 /// elapse. Therefore, this penalty will never decay.
231 ///
232 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
233 #[no_mangle]
234 pub extern "C" fn ScoringParameters_set_failure_penalty_half_life(this_ptr: &mut ScoringParameters, mut val: u64) {
235         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure_penalty_half_life = std::time::Duration::from_secs(val);
236 }
237 /// Constructs a new ScoringParameters given each field
238 #[must_use]
239 #[no_mangle]
240 pub extern "C" fn ScoringParameters_new(mut base_penalty_msat_arg: u64, mut failure_penalty_msat_arg: u64, mut failure_penalty_half_life_arg: u64) -> ScoringParameters {
241         ScoringParameters { inner: ObjOps::heap_alloc(nativeScoringParameters {
242                 base_penalty_msat: base_penalty_msat_arg,
243                 failure_penalty_msat: failure_penalty_msat_arg,
244                 failure_penalty_half_life: std::time::Duration::from_secs(failure_penalty_half_life_arg),
245         }), is_owned: true }
246 }
247 #[no_mangle]
248 /// Serialize the ScoringParameters object into a byte array which can be read by ScoringParameters_read
249 pub extern "C" fn ScoringParameters_write(obj: &ScoringParameters) -> crate::c_types::derived::CVec_u8Z {
250         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
251 }
252 #[no_mangle]
253 pub(crate) extern "C" fn ScoringParameters_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
254         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeScoringParameters) })
255 }
256 #[no_mangle]
257 /// Read a ScoringParameters from a byte array, created by ScoringParameters_write
258 pub extern "C" fn ScoringParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ScoringParametersDecodeErrorZ {
259         let res: Result<lightning::routing::scorer::ScoringParameters, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
260         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scorer::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() };
261         local_res
262 }
263 /// Creates a new scorer using the given scoring parameters.
264 #[must_use]
265 #[no_mangle]
266 pub extern "C" fn Scorer_new(mut params: crate::lightning::routing::scorer::ScoringParameters) -> Scorer {
267         let mut ret = lightning::routing::scorer::Scorer::new(*unsafe { Box::from_raw(params.take_inner()) });
268         Scorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
269 }
270
271 /// Creates a "default" Scorer. See struct and individual field documentaiton for details on which values are used.
272 #[must_use]
273 #[no_mangle]
274 pub extern "C" fn Scorer_default() -> Scorer {
275         Scorer { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
276 }
277 /// Creates a "default" ScoringParameters. See struct and individual field documentaiton for details on which values are used.
278 #[must_use]
279 #[no_mangle]
280 pub extern "C" fn ScoringParameters_default() -> ScoringParameters {
281         ScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
282 }
283 impl From<nativeScorer> for crate::lightning::routing::Score {
284         fn from(obj: nativeScorer) -> Self {
285                 let mut rust_obj = Scorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
286                 let mut ret = Scorer_as_Score(&rust_obj);
287                 // 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
288                 rust_obj.inner = std::ptr::null_mut();
289                 ret.free = Some(Scorer_free_void);
290                 ret
291         }
292 }
293 /// Constructs a new Score which calls the relevant methods on this_arg.
294 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
295 #[no_mangle]
296 pub extern "C" fn Scorer_as_Score(this_arg: &Scorer) -> crate::lightning::routing::Score {
297         crate::lightning::routing::Score {
298                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
299                 free: None,
300                 channel_penalty_msat: Scorer_Score_channel_penalty_msat,
301                 payment_path_failed: Scorer_Score_payment_path_failed,
302                 write: Scorer_write_void,
303         }
304 }
305
306 #[must_use]
307 extern "C" fn Scorer_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, _source: &crate::lightning::routing::network_graph::NodeId, _target: &crate::lightning::routing::network_graph::NodeId) -> u64 {
308         let mut ret = <nativeScorer as lightning::routing::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeScorer) }, short_channel_id, _source.get_native_ref(), _target.get_native_ref());
309         ret
310 }
311 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) {
312         let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
313         <nativeScorer as lightning::routing::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeScorer) }, &local__path[..], short_channel_id)
314 }
315
316 #[no_mangle]
317 /// Serialize the Scorer object into a byte array which can be read by Scorer_read
318 pub extern "C" fn Scorer_write(obj: &Scorer) -> crate::c_types::derived::CVec_u8Z {
319         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
320 }
321 #[no_mangle]
322 pub(crate) extern "C" fn Scorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
323         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeScorer) })
324 }
325 #[no_mangle]
326 /// Read a Scorer from a byte array, created by Scorer_write
327 pub extern "C" fn Scorer_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ScorerDecodeErrorZ {
328         let res: Result<lightning::routing::scorer::Scorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
329         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scorer::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() };
330         local_res
331 }