1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
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.
9 //! Utilities for scoring payment channels.
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.
17 //! # extern crate secp256k1;
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;
25 //! # struct FakeLogger {};
26 //! # impl Logger for FakeLogger {
27 //! # fn log(&self, record: &Record) { unimplemented!() }
29 //! # fn find_scored_route(payer: PublicKey, params: RouteParameters, network_graph: NetworkGraph) {
30 //! # let logger = FakeLogger {};
32 //! // Use the default channel penalties.
33 //! let scorer = Scorer::default();
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()
42 //! let route = find_route(&payer, ¶ms, &network_graph, None, &logger, &scorer);
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.
52 //! [`find_route`]: crate::routing::router::find_route
54 use std::str::FromStr;
56 use core::convert::Infallible;
57 use bitcoin::hashes::Hash;
58 use crate::c_types::*;
62 use std::str::FromStr;
64 use core::convert::Infallible;
65 use bitcoin::hashes::Hash;
66 use crate::c_types::*;
70 use lightning::routing::scorer::Scorer as nativeScorerImport;
71 pub(crate) type nativeScorer = nativeScorerImport;
73 /// [`routing::Score`] implementation that provides reasonable default behavior.
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.
78 /// See [module-level documentation] for usage.
80 /// [module-level documentation]: crate::routing::scorer
84 /// A pointer to the opaque Rust object.
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.
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.
96 impl Drop for Scorer {
98 if self.is_owned && !<*mut nativeScorer>::is_null(self.inner) {
99 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
103 /// Frees any resources used by the Scorer, if is_owned is set and inner is non-NULL.
105 pub extern "C" fn Scorer_free(this_obj: Scorer) { }
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); }
113 pub(crate) fn get_native_ref(&self) -> &'static nativeScorer {
114 unsafe { &*ObjOps::untweak_ptr(self.inner) }
116 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeScorer {
117 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
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();
128 use lightning::routing::scorer::ScoringParameters as nativeScoringParametersImport;
129 pub(crate) type nativeScoringParameters = nativeScoringParametersImport;
131 /// Parameters for configuring [`Scorer`].
134 pub struct ScoringParameters {
135 /// A pointer to the opaque Rust object.
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.
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.
147 impl Drop for ScoringParameters {
149 if self.is_owned && !<*mut nativeScoringParameters>::is_null(self.inner) {
150 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
154 /// Frees any resources used by the ScoringParameters, if is_owned is set and inner is non-NULL.
156 pub extern "C" fn ScoringParameters_free(this_obj: ScoringParameters) { }
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); }
163 impl ScoringParameters {
164 pub(crate) fn get_native_ref(&self) -> &'static nativeScoringParameters {
165 unsafe { &*ObjOps::untweak_ptr(self.inner) }
167 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeScoringParameters {
168 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
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();
178 /// A fixed penalty in msats to apply to each channel.
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;
184 /// A fixed penalty in msats to apply to each channel.
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;
189 /// A penalty in msats to apply to a channel upon failing to relay a payment.
191 /// This accumulates for each failure but may be reduced over time based on
192 /// [`failure_penalty_half_life`].
194 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
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;
200 /// A penalty in msats to apply to a channel upon failing to relay a payment.
202 /// This accumulates for each failure but may be reduced over time based on
203 /// [`failure_penalty_half_life`].
205 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
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;
210 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
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.
218 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
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;
224 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
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.
232 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
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);
237 /// Constructs a new ScoringParameters given each field
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),
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())
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) })
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() };
263 /// Creates a new scorer using the given scoring parameters.
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 }
271 /// Creates a "default" Scorer. See struct and individual field documentaiton for details on which values are used.
274 pub extern "C" fn Scorer_default() -> Scorer {
275 Scorer { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
277 /// Creates a "default" ScoringParameters. See struct and individual field documentaiton for details on which values are used.
280 pub extern "C" fn ScoringParameters_default() -> ScoringParameters {
281 ScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
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);
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
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 },
300 channel_penalty_msat: Scorer_Score_channel_penalty_msat,
301 payment_path_failed: Scorer_Score_payment_path_failed,
302 write: Scorer_write_void,
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());
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)
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())
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) })
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() };