X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning-c-bindings%2Fsrc%2Flightning%2Frouting%2Fscoring.rs;h=0923a5598d8597308f626539383a3e3812920ace;hb=3fafbe3b1625eb163737b705bac7e2f911b53bdb;hp=bc3af0acfedf6141edabe966274d99a4e5b77735;hpb=23b946be5cf633afdba94e12fd71380cafdf49be;p=ldk-c-bindings diff --git a/lightning-c-bindings/src/lightning/routing/scoring.rs b/lightning-c-bindings/src/lightning/routing/scoring.rs index bc3af0a..0923a55 100644 --- a/lightning-c-bindings/src/lightning/routing/scoring.rs +++ b/lightning-c-bindings/src/lightning/routing/scoring.rs @@ -8,8 +8,8 @@ //! Utilities for scoring payment channels. //! -//! [`Scorer`] may be given to [`find_route`] to score payment channels during path finding when a -//! custom [`Score`] implementation is not needed. +//! [`ProbabilisticScorer`] may be given to [`find_route`] to score payment channels during path +//! finding when a custom [`Score`] implementation is not needed. //! //! # Example //! @@ -18,7 +18,8 @@ //! # //! # use lightning::routing::network_graph::NetworkGraph; //! # use lightning::routing::router::{RouteParameters, find_route}; -//! # use lightning::routing::scoring::{Scorer, ScoringParameters}; +//! # use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters, Scorer, ScoringParameters}; +//! # use lightning::chain::keysinterface::{KeysManager, KeysInterface}; //! # use lightning::util::logger::{Logger, Record}; //! # use secp256k1::key::PublicKey; //! # @@ -26,20 +27,22 @@ //! # impl Logger for FakeLogger { //! # fn log(&self, record: &Record) { unimplemented!() } //! # } -//! # fn find_scored_route(payer: PublicKey, params: RouteParameters, network_graph: NetworkGraph) { +//! # fn find_scored_route(payer: PublicKey, route_params: RouteParameters, network_graph: NetworkGraph) { //! # let logger = FakeLogger {}; //! # //! // Use the default channel penalties. -//! let scorer = Scorer::default(); +//! let params = ProbabilisticScoringParameters::default(); +//! let scorer = ProbabilisticScorer::new(params, &network_graph); //! //! // Or use custom channel penalties. -//! let scorer = Scorer::new(ScoringParameters { -//! base_penalty_msat: 1000, -//! failure_penalty_msat: 2 * 1024 * 1000, -//! ..ScoringParameters::default() -//! }); +//! let params = ProbabilisticScoringParameters { +//! liquidity_penalty_multiplier_msat: 2 * 1000, +//! ..ProbabilisticScoringParameters::default() +//! }; +//! let scorer = ProbabilisticScorer::new(params, &network_graph); +//! # let random_seed_bytes = [42u8; 32]; //! -//! let route = find_route(&payer, ¶ms, &network_graph, None, &logger, &scorer); +//! let route = find_route(&payer, &route_params, &network_graph, None, &logger, &scorer, &random_seed_bytes); //! # } //! ``` //! @@ -50,11 +53,13 @@ //! //! [`find_route`]: crate::routing::router::find_route -use std::str::FromStr; -use std::ffi::c_void; +use alloc::str::FromStr; +use core::ffi::c_void; use core::convert::Infallible; use bitcoin::hashes::Hash; use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; /// An interface used to score payment channels for path finding. /// @@ -67,17 +72,13 @@ pub struct Score { /// Returns the fee in msats willing to be paid to avoid routing `send_amt_msat` through the /// given channel in the direction from `source` to `target`. /// - /// The channel's capacity (less any other MPP parts which are also being considered for use in - /// the same payment) is given by `channel_capacity_msat`. It may be guessed from various - /// sources or assumed from no data at all. - /// - /// For hints provided in the invoice, we assume the channel has sufficient capacity to accept - /// the invoice's full amount, and provide a `channel_capacity_msat` of `None`. In all other - /// cases it is set to `Some`, even if we're guessing at the channel value. - /// - /// Your code should be overflow-safe through a `channel_capacity_msat` of 21 million BTC. + /// The channel's capacity (less any other MPP parts that are also being considered for use in + /// the same payment) is given by `capacity_msat`. It may be determined from various sources + /// such as a chain data, network gossip, or invoice hints. For invoice hints, a capacity near + /// [`u64::max_value`] is given to indicate sufficient capacity for the invoice's full amount. + /// Thus, implementations should be overflow-safe. #[must_use] - 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, + pub channel_penalty_msat: extern "C" fn (this_arg: *const c_void, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, source: &crate::lightning::routing::network_graph::NodeId, target: &crate::lightning::routing::network_graph::NodeId) -> u64, /// Handles updating channel penalties after failing to route through a channel. pub payment_path_failed: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ, short_channel_id: u64), /// Handles updating channel penalties after successfully routing along a path. @@ -102,7 +103,7 @@ pub(crate) extern "C" fn Score_clone_fields(orig: &Score) -> Score { } } impl lightning::util::ser::Writeable for Score { - fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { + fn write(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> { let vec = (self.write)(self.this_arg); w.write_all(vec.as_slice()) } @@ -110,9 +111,8 @@ impl lightning::util::ser::Writeable for Score { use lightning::routing::scoring::Score as rustScore; impl rustScore for Score { - fn channel_penalty_msat(&self, mut short_channel_id: u64, mut send_amt_msat: u64, mut channel_capacity_msat: Option, mut source: &lightning::routing::network_graph::NodeId, mut target: &lightning::routing::network_graph::NodeId) -> u64 { - 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() }) }; - 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 }); + fn channel_penalty_msat(&self, mut short_channel_id: u64, mut send_amt_msat: u64, mut capacity_msat: u64, mut source: &lightning::routing::network_graph::NodeId, mut target: &lightning::routing::network_graph::NodeId) -> u64 { + let mut ret = (self.channel_penalty_msat)(self.this_arg, short_channel_id, send_amt_msat, capacity_msat, &crate::lightning::routing::network_graph::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((source as *const lightning::routing::network_graph::NodeId<>) as *mut _) }, is_owned: false }, &crate::lightning::routing::network_graph::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((target as *const lightning::routing::network_graph::NodeId<>) as *mut _) }, is_owned: false }); ret } fn payment_path_failed(&mut self, mut path: &[&lightning::routing::router::RouteHop], mut short_channel_id: u64) { @@ -127,7 +127,7 @@ impl rustScore for Score { // We're essentially a pointer already, or at least a set of pointers, so allow us to be used // directly as a Deref trait in higher-level structs: -impl std::ops::Deref for Score { +impl core::ops::Deref for Score { type Target = Self; fn deref(&self) -> &Self { self @@ -185,7 +185,7 @@ impl<'a> rustLockableScore<'a> for LockableScore { // We're essentially a pointer already, or at least a set of pointers, so allow us to be used // directly as a Deref trait in higher-level structs: -impl std::ops::Deref for LockableScore { +impl core::ops::Deref for LockableScore { type Target = Self; fn deref(&self) -> &Self { self @@ -248,18 +248,151 @@ impl MultiThreadedLockableScore { pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedLockableScore { assert!(self.is_owned); let ret = ObjOps::untweak_ptr(self.inner); - self.inner = std::ptr::null_mut(); + self.inner = core::ptr::null_mut(); ret } } /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`]. #[must_use] #[no_mangle] -pub extern "C" fn MultiThreadedLockableScore_new(mut score: crate::lightning::routing::scoring::Score) -> MultiThreadedLockableScore { +pub extern "C" fn MultiThreadedLockableScore_new(mut score: crate::lightning::routing::scoring::Score) -> crate::lightning::routing::scoring::MultiThreadedLockableScore { let mut ret = lightning::routing::scoring::MultiThreadedLockableScore::new(score); - MultiThreadedLockableScore { inner: ObjOps::heap_alloc(ret), is_owned: true } + crate::lightning::routing::scoring::MultiThreadedLockableScore { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + + +use lightning::routing::scoring::FixedPenaltyScorer as nativeFixedPenaltyScorerImport; +pub(crate) type nativeFixedPenaltyScorer = nativeFixedPenaltyScorerImport; + +/// [`Score`] implementation that uses a fixed penalty. +#[must_use] +#[repr(C)] +pub struct FixedPenaltyScorer { + /// A pointer to the opaque Rust object. + + /// Nearly everywhere, inner must be non-null, however in places where + /// the Rust equivalent takes an Option, it may be set to null to indicate None. + pub inner: *mut nativeFixedPenaltyScorer, + /// Indicates that this is the only struct which contains the same pointer. + + /// Rust functions which take ownership of an object provided via an argument require + /// this to be true and invalidate the object pointed to by inner. + pub is_owned: bool, +} + +impl Drop for FixedPenaltyScorer { + fn drop(&mut self) { + if self.is_owned && !<*mut nativeFixedPenaltyScorer>::is_null(self.inner) { + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; + } + } +} +/// Frees any resources used by the FixedPenaltyScorer, if is_owned is set and inner is non-NULL. +#[no_mangle] +pub extern "C" fn FixedPenaltyScorer_free(this_obj: FixedPenaltyScorer) { } +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn FixedPenaltyScorer_free_void(this_ptr: *mut c_void) { + unsafe { let _ = Box::from_raw(this_ptr as *mut nativeFixedPenaltyScorer); } +} +#[allow(unused)] +impl FixedPenaltyScorer { + pub(crate) fn get_native_ref(&self) -> &'static nativeFixedPenaltyScorer { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFixedPenaltyScorer { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy + pub(crate) fn take_inner(mut self) -> *mut nativeFixedPenaltyScorer { + assert!(self.is_owned); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); + ret + } +} +impl Clone for FixedPenaltyScorer { + fn clone(&self) -> Self { + Self { + inner: if <*mut nativeFixedPenaltyScorer>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, + is_owned: true, + } + } +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn FixedPenaltyScorer_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFixedPenaltyScorer)).clone() })) as *mut c_void +} +#[no_mangle] +/// Creates a copy of the FixedPenaltyScorer +pub extern "C" fn FixedPenaltyScorer_clone(orig: &FixedPenaltyScorer) -> FixedPenaltyScorer { + orig.clone() +} +/// Creates a new scorer using `penalty_msat`. +#[must_use] +#[no_mangle] +pub extern "C" fn FixedPenaltyScorer_with_penalty(mut penalty_msat: u64) -> crate::lightning::routing::scoring::FixedPenaltyScorer { + let mut ret = lightning::routing::scoring::FixedPenaltyScorer::with_penalty(penalty_msat); + crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(ret), is_owned: true } } +impl From for crate::lightning::routing::scoring::Score { + fn from(obj: nativeFixedPenaltyScorer) -> Self { + let mut rust_obj = FixedPenaltyScorer { inner: ObjOps::heap_alloc(obj), is_owned: true }; + let mut ret = FixedPenaltyScorer_as_Score(&rust_obj); + // 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 + rust_obj.inner = core::ptr::null_mut(); + ret.free = Some(FixedPenaltyScorer_free_void); + ret + } +} +/// Constructs a new Score which calls the relevant methods on this_arg. +/// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is +#[no_mangle] +pub extern "C" fn FixedPenaltyScorer_as_Score(this_arg: &FixedPenaltyScorer) -> crate::lightning::routing::scoring::Score { + crate::lightning::routing::scoring::Score { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, + free: None, + channel_penalty_msat: FixedPenaltyScorer_Score_channel_penalty_msat, + payment_path_failed: FixedPenaltyScorer_Score_payment_path_failed, + payment_path_successful: FixedPenaltyScorer_Score_payment_path_successful, + write: FixedPenaltyScorer_write_void, + } +} + +#[must_use] +extern "C" fn FixedPenaltyScorer_Score_channel_penalty_msat(this_arg: *const c_void, unused_0: u64, unused_1: u64, unused_2: u64, unused_3: &crate::lightning::routing::network_graph::NodeId, unused_4: &crate::lightning::routing::network_graph::NodeId) -> u64 { + let mut ret = >::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, unused_0, unused_1, unused_2, unused_3.get_native_ref(), unused_4.get_native_ref()); + ret +} +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) { + let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); }; + >::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..], _short_channel_id) +} +extern "C" fn FixedPenaltyScorer_Score_payment_path_successful(this_arg: *mut c_void, mut _path: crate::c_types::derived::CVec_RouteHopZ) { + let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); }; + >::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..]) +} + +#[no_mangle] +/// Serialize the FixedPenaltyScorer object into a byte array which can be read by FixedPenaltyScorer_read +pub extern "C" fn FixedPenaltyScorer_write(obj: &crate::lightning::routing::scoring::FixedPenaltyScorer) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) +} +#[no_mangle] +pub(crate) extern "C" fn FixedPenaltyScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFixedPenaltyScorer) }) +} +#[no_mangle] +/// Read a FixedPenaltyScorer from a byte array, created by FixedPenaltyScorer_write +pub extern "C" fn FixedPenaltyScorer_read(ser: crate::c_types::u8slice, arg: u64) -> crate::c_types::derived::CResult_FixedPenaltyScorerDecodeErrorZ { + let arg_conv = arg; + let res: Result = crate::c_types::deserialize_obj_arg(ser, arg_conv); + 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() }; + local_res +} use lightning::routing::scoring::Scorer as nativeScorerImport; pub(crate) type nativeScorer = nativeScorerImport; @@ -269,7 +402,12 @@ pub(crate) type nativeScorer = nativeScorerImport; /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with /// slightly higher fees are available. Will further penalize channels that fail to relay payments. /// -/// See [module-level documentation] for usage. +/// See [module-level documentation] for usage and [`ScoringParameters`] for customization. +/// +/// # Note +/// +/// Mixing the `no-std` feature between serialization and deserialization results in undefined +/// behavior. /// /// [module-level documentation]: crate::routing::scoring #[must_use] @@ -314,7 +452,7 @@ impl Scorer { pub(crate) fn take_inner(mut self) -> *mut nativeScorer { assert!(self.is_owned); let ret = ObjOps::untweak_ptr(self.inner); - self.inner = std::ptr::null_mut(); + self.inner = core::ptr::null_mut(); ret } } @@ -365,7 +503,7 @@ impl ScoringParameters { pub(crate) fn take_inner(mut self) -> *mut nativeScoringParameters { assert!(self.is_owned); let ret = ObjOps::untweak_ptr(self.inner); - self.inner = std::ptr::null_mut(); + self.inner = core::ptr::null_mut(); ret } } @@ -458,6 +596,8 @@ pub extern "C" fn ScoringParameters_set_overuse_penalty_msat_per_1024th(this_ptr /// /// Successfully routing through a channel will immediately cut the penalty in half as well. /// +/// Default value: 1 hour +/// /// # Note /// /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will @@ -474,6 +614,8 @@ pub extern "C" fn ScoringParameters_get_failure_penalty_half_life(this_ptr: &Sco /// /// Successfully routing through a channel will immediately cut the penalty in half as well. /// +/// Default value: 1 hour +/// /// # Note /// /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will @@ -482,7 +624,7 @@ pub extern "C" fn ScoringParameters_get_failure_penalty_half_life(this_ptr: &Sco /// [`failure_penalty_msat`]: Self::failure_penalty_msat #[no_mangle] pub extern "C" fn ScoringParameters_set_failure_penalty_half_life(this_ptr: &mut ScoringParameters, mut val: u64) { - unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure_penalty_half_life = std::time::Duration::from_secs(val); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure_penalty_half_life = core::time::Duration::from_secs(val); } /// Constructs a new ScoringParameters given each field #[must_use] @@ -493,12 +635,31 @@ pub extern "C" fn ScoringParameters_new(mut base_penalty_msat_arg: u64, mut fail failure_penalty_msat: failure_penalty_msat_arg, overuse_penalty_start_1024th: overuse_penalty_start_1024th_arg, overuse_penalty_msat_per_1024th: overuse_penalty_msat_per_1024th_arg, - failure_penalty_half_life: std::time::Duration::from_secs(failure_penalty_half_life_arg), + failure_penalty_half_life: core::time::Duration::from_secs(failure_penalty_half_life_arg), }), is_owned: true } } +impl Clone for ScoringParameters { + fn clone(&self) -> Self { + Self { + inner: if <*mut nativeScoringParameters>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, + is_owned: true, + } + } +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn ScoringParameters_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeScoringParameters)).clone() })) as *mut c_void +} +#[no_mangle] +/// Creates a copy of the ScoringParameters +pub extern "C" fn ScoringParameters_clone(orig: &ScoringParameters) -> ScoringParameters { + orig.clone() +} #[no_mangle] /// Serialize the ScoringParameters object into a byte array which can be read by ScoringParameters_read -pub extern "C" fn ScoringParameters_write(obj: &ScoringParameters) -> crate::c_types::derived::CVec_u8Z { +pub extern "C" fn ScoringParameters_write(obj: &crate::lightning::routing::scoring::ScoringParameters) -> crate::c_types::derived::CVec_u8Z { crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] @@ -515,9 +676,9 @@ pub extern "C" fn ScoringParameters_read(ser: crate::c_types::u8slice) -> crate: /// Creates a new scorer using the given scoring parameters. #[must_use] #[no_mangle] -pub extern "C" fn Scorer_new(mut params: crate::lightning::routing::scoring::ScoringParameters) -> Scorer { +pub extern "C" fn Scorer_new(mut params: crate::lightning::routing::scoring::ScoringParameters) -> crate::lightning::routing::scoring::Scorer { let mut ret = lightning::routing::scoring::Scorer::new(*unsafe { Box::from_raw(params.take_inner()) }); - Scorer { inner: ObjOps::heap_alloc(ret), is_owned: true } + crate::lightning::routing::scoring::Scorer { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Creates a "default" Scorer. See struct and individual field documentaiton for details on which values are used. @@ -537,7 +698,7 @@ impl From for crate::lightning::routing::scoring::Score { let mut rust_obj = Scorer { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = Scorer_as_Score(&rust_obj); // 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 - rust_obj.inner = std::ptr::null_mut(); + rust_obj.inner = core::ptr::null_mut(); ret.free = Some(Scorer_free_void); ret } @@ -557,9 +718,8 @@ pub extern "C" fn Scorer_as_Score(this_arg: &Scorer) -> crate::lightning::routin } #[must_use] -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 { - let mut local_chan_capacity_opt = if chan_capacity_opt.is_some() { Some( { chan_capacity_opt.take() }) } else { None }; - let mut ret = >::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()); +extern "C" fn Scorer_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, mut send_amt_msat: u64, mut capacity_msat: u64, _source: &crate::lightning::routing::network_graph::NodeId, _target: &crate::lightning::routing::network_graph::NodeId) -> u64 { + let mut ret = >::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeScorer) }, short_channel_id, send_amt_msat, capacity_msat, _source.get_native_ref(), _target.get_native_ref()); ret } 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) { @@ -573,7 +733,7 @@ extern "C" fn Scorer_Score_payment_path_successful(this_arg: *mut c_void, mut pa #[no_mangle] /// Serialize the Scorer object into a byte array which can be read by Scorer_read -pub extern "C" fn Scorer_write(obj: &Scorer) -> crate::c_types::derived::CVec_u8Z { +pub extern "C" fn Scorer_write(obj: &crate::lightning::routing::scoring::Scorer) -> crate::c_types::derived::CVec_u8Z { crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] @@ -587,12 +747,381 @@ pub extern "C" fn Scorer_read(ser: crate::c_types::u8slice) -> crate::c_types::d 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() }; local_res } + +use lightning::routing::scoring::ProbabilisticScorer as nativeProbabilisticScorerImport; +pub(crate) type nativeProbabilisticScorer = nativeProbabilisticScorerImport<&'static lightning::routing::network_graph::NetworkGraph>; + +/// [`Score`] implementation using channel success probability distributions. +/// +/// Based on *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt +/// and Stefan Richter [[1]]. Given the uncertainty of channel liquidity balances, probability +/// distributions are defined based on knowledge learned from successful and unsuccessful attempts. +/// Then the negative `log10` of the success probability is used to determine the cost of routing a +/// specific HTLC amount through a channel. +/// +/// Knowledge about channel liquidity balances takes the form of upper and lower bounds on the +/// possible liquidity. Certainty of the bounds is decreased over time using a decay function. See +/// [`ProbabilisticScoringParameters`] for details. +/// +/// Since the scorer aims to learn the current channel liquidity balances, it works best for nodes +/// with high payment volume or that actively probe the [`NetworkGraph`]. Nodes with low payment +/// volume are more likely to experience failed payment paths, which would need to be retried. +/// +/// # Note +/// +/// Mixing the `no-std` feature between serialization and deserialization results in undefined +/// behavior. +/// +/// [1]: https://arxiv.org/abs/2107.05322 +#[must_use] +#[repr(C)] +pub struct ProbabilisticScorer { + /// A pointer to the opaque Rust object. + + /// Nearly everywhere, inner must be non-null, however in places where + /// the Rust equivalent takes an Option, it may be set to null to indicate None. + pub inner: *mut nativeProbabilisticScorer, + /// Indicates that this is the only struct which contains the same pointer. + + /// Rust functions which take ownership of an object provided via an argument require + /// this to be true and invalidate the object pointed to by inner. + pub is_owned: bool, +} + +impl Drop for ProbabilisticScorer { + fn drop(&mut self) { + if self.is_owned && !<*mut nativeProbabilisticScorer>::is_null(self.inner) { + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; + } + } +} +/// Frees any resources used by the ProbabilisticScorer, if is_owned is set and inner is non-NULL. +#[no_mangle] +pub extern "C" fn ProbabilisticScorer_free(this_obj: ProbabilisticScorer) { } +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn ProbabilisticScorer_free_void(this_ptr: *mut c_void) { + unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScorer); } +} +#[allow(unused)] +impl ProbabilisticScorer { + pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScorer { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScorer { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy + pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScorer { + assert!(self.is_owned); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); + ret + } +} + +use lightning::routing::scoring::ProbabilisticScoringParameters as nativeProbabilisticScoringParametersImport; +pub(crate) type nativeProbabilisticScoringParameters = nativeProbabilisticScoringParametersImport; + +/// Parameters for configuring [`ProbabilisticScorer`]. +/// +/// Used to configure base, liquidity, and amount penalties, the sum of which comprises the channel +/// penalty (i.e., the amount in msats willing to be paid to avoid routing through the channel). +#[must_use] +#[repr(C)] +pub struct ProbabilisticScoringParameters { + /// A pointer to the opaque Rust object. + + /// Nearly everywhere, inner must be non-null, however in places where + /// the Rust equivalent takes an Option, it may be set to null to indicate None. + pub inner: *mut nativeProbabilisticScoringParameters, + /// Indicates that this is the only struct which contains the same pointer. + + /// Rust functions which take ownership of an object provided via an argument require + /// this to be true and invalidate the object pointed to by inner. + pub is_owned: bool, +} + +impl Drop for ProbabilisticScoringParameters { + fn drop(&mut self) { + if self.is_owned && !<*mut nativeProbabilisticScoringParameters>::is_null(self.inner) { + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; + } + } +} +/// Frees any resources used by the ProbabilisticScoringParameters, if is_owned is set and inner is non-NULL. +#[no_mangle] +pub extern "C" fn ProbabilisticScoringParameters_free(this_obj: ProbabilisticScoringParameters) { } +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn ProbabilisticScoringParameters_free_void(this_ptr: *mut c_void) { + unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScoringParameters); } +} +#[allow(unused)] +impl ProbabilisticScoringParameters { + pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringParameters { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringParameters { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy + pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringParameters { + assert!(self.is_owned); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); + ret + } +} +/// A fixed penalty in msats to apply to each channel. +/// +/// Default value: 500 msat +#[no_mangle] +pub extern "C" fn ProbabilisticScoringParameters_get_base_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat; + *inner_val +} +/// A fixed penalty in msats to apply to each channel. +/// +/// Default value: 500 msat +#[no_mangle] +pub extern "C" fn ProbabilisticScoringParameters_set_base_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val; +} +/// A multiplier used in conjunction with the negative `log10` of the channel's success +/// probability for a payment to determine the liquidity penalty. +/// +/// The penalty is based in part on the knowledge learned from prior successful and unsuccessful +/// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The +/// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to +/// lower bounding the success probability to `0.01`) when the amount falls within the +/// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will +/// result in a `u64::max_value` penalty, however. +/// +/// Default value: 40,000 msat +/// +/// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life +#[no_mangle] +pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_multiplier_msat; + *inner_val +} +/// A multiplier used in conjunction with the negative `log10` of the channel's success +/// probability for a payment to determine the liquidity penalty. +/// +/// The penalty is based in part on the knowledge learned from prior successful and unsuccessful +/// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The +/// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to +/// lower bounding the success probability to `0.01`) when the amount falls within the +/// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will +/// result in a `u64::max_value` penalty, however. +/// +/// Default value: 40,000 msat +/// +/// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life +#[no_mangle] +pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_multiplier_msat = val; +} +/// The time required to elapse before any knowledge learned about channel liquidity balances is +/// cut in half. +/// +/// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets +/// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases +/// the certainty of the channel liquidity balance. +/// +/// Default value: 1 hour +/// +/// # Note +/// +/// When built with the `no-std` feature, time will never elapse. Therefore, the channel +/// liquidity knowledge will never decay except when the bounds cross. +#[no_mangle] +pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_offset_half_life(this_ptr: &ProbabilisticScoringParameters) -> u64 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_offset_half_life; + inner_val.as_secs() +} +/// The time required to elapse before any knowledge learned about channel liquidity balances is +/// cut in half. +/// +/// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets +/// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases +/// the certainty of the channel liquidity balance. +/// +/// Default value: 1 hour +/// +/// # Note +/// +/// When built with the `no-std` feature, time will never elapse. Therefore, the channel +/// liquidity knowledge will never decay except when the bounds cross. +#[no_mangle] +pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_offset_half_life(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_offset_half_life = core::time::Duration::from_secs(val); +} +/// A multiplier used in conjunction with a payment amount and the negative `log10` of the +/// channel's success probability for the payment to determine the amount penalty. +/// +/// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e., +/// fees plus penalty) for large payments. The penalty is computed as the product of this +/// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the +/// success probability. +/// +/// `-log10(success_probability) * amount_penalty_multiplier_msat * amount_msat / 2^20` +/// +/// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of +/// the amount will result in a penalty of the multiplier. And, as the success probability +/// decreases, the negative `log10` weighting will increase dramatically. For higher success +/// probabilities, the multiplier will have a decreasing effect as the negative `log10` will +/// fall below `1`. +/// +/// Default value: 256 msat +#[no_mangle] +pub extern "C" fn ProbabilisticScoringParameters_get_amount_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_penalty_multiplier_msat; + *inner_val +} +/// A multiplier used in conjunction with a payment amount and the negative `log10` of the +/// channel's success probability for the payment to determine the amount penalty. +/// +/// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e., +/// fees plus penalty) for large payments. The penalty is computed as the product of this +/// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the +/// success probability. +/// +/// `-log10(success_probability) * amount_penalty_multiplier_msat * amount_msat / 2^20` +/// +/// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of +/// the amount will result in a penalty of the multiplier. And, as the success probability +/// decreases, the negative `log10` weighting will increase dramatically. For higher success +/// probabilities, the multiplier will have a decreasing effect as the negative `log10` will +/// fall below `1`. +/// +/// Default value: 256 msat +#[no_mangle] +pub extern "C" fn ProbabilisticScoringParameters_set_amount_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_penalty_multiplier_msat = val; +} +/// Constructs a new ProbabilisticScoringParameters given each field +#[must_use] +#[no_mangle] +pub extern "C" fn ProbabilisticScoringParameters_new(mut base_penalty_msat_arg: u64, mut liquidity_penalty_multiplier_msat_arg: u64, mut liquidity_offset_half_life_arg: u64, mut amount_penalty_multiplier_msat_arg: u64) -> ProbabilisticScoringParameters { + ProbabilisticScoringParameters { inner: ObjOps::heap_alloc(nativeProbabilisticScoringParameters { + base_penalty_msat: base_penalty_msat_arg, + liquidity_penalty_multiplier_msat: liquidity_penalty_multiplier_msat_arg, + liquidity_offset_half_life: core::time::Duration::from_secs(liquidity_offset_half_life_arg), + amount_penalty_multiplier_msat: amount_penalty_multiplier_msat_arg, + }), is_owned: true } +} +impl Clone for ProbabilisticScoringParameters { + fn clone(&self) -> Self { + Self { + inner: if <*mut nativeProbabilisticScoringParameters>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, + is_owned: true, + } + } +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn ProbabilisticScoringParameters_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeProbabilisticScoringParameters)).clone() })) as *mut c_void +} +#[no_mangle] +/// Creates a copy of the ProbabilisticScoringParameters +pub extern "C" fn ProbabilisticScoringParameters_clone(orig: &ProbabilisticScoringParameters) -> ProbabilisticScoringParameters { + orig.clone() +} +/// Creates a new scorer using the given scoring parameters for sending payments from a node +/// through a network graph. +#[must_use] +#[no_mangle] +pub extern "C" fn ProbabilisticScorer_new(mut params: crate::lightning::routing::scoring::ProbabilisticScoringParameters, network_graph: &crate::lightning::routing::network_graph::NetworkGraph) -> crate::lightning::routing::scoring::ProbabilisticScorer { + let mut ret = lightning::routing::scoring::ProbabilisticScorer::new(*unsafe { Box::from_raw(params.take_inner()) }, network_graph.get_native_ref()); + crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + +/// Creates a "default" ProbabilisticScoringParameters. See struct and individual field documentaiton for details on which values are used. +#[must_use] +#[no_mangle] +pub extern "C" fn ProbabilisticScoringParameters_default() -> ProbabilisticScoringParameters { + ProbabilisticScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true } +} +impl From for crate::lightning::routing::scoring::Score { + fn from(obj: nativeProbabilisticScorer) -> Self { + let mut rust_obj = ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true }; + let mut ret = ProbabilisticScorer_as_Score(&rust_obj); + // 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 + rust_obj.inner = core::ptr::null_mut(); + ret.free = Some(ProbabilisticScorer_free_void); + ret + } +} +/// Constructs a new Score which calls the relevant methods on this_arg. +/// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is +#[no_mangle] +pub extern "C" fn ProbabilisticScorer_as_Score(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::Score { + crate::lightning::routing::scoring::Score { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, + free: None, + channel_penalty_msat: ProbabilisticScorer_Score_channel_penalty_msat, + payment_path_failed: ProbabilisticScorer_Score_payment_path_failed, + payment_path_successful: ProbabilisticScorer_Score_payment_path_successful, + write: ProbabilisticScorer_write_void, + } +} + +#[must_use] +extern "C" fn ProbabilisticScorer_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, mut amount_msat: u64, mut capacity_msat: u64, source: &crate::lightning::routing::network_graph::NodeId, target: &crate::lightning::routing::network_graph::NodeId) -> u64 { + let mut ret = >::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, short_channel_id, amount_msat, capacity_msat, source.get_native_ref(), target.get_native_ref()); + ret +} +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) { + let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); }; + >::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..], short_channel_id) +} +extern "C" fn ProbabilisticScorer_Score_payment_path_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) { + let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); }; + >::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..]) +} + +mod approx { + +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; +use bitcoin::hashes::Hash; +use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; + +} +#[no_mangle] +/// Serialize the ProbabilisticScorer object into a byte array which can be read by ProbabilisticScorer_read +pub extern "C" fn ProbabilisticScorer_write(obj: &crate::lightning::routing::scoring::ProbabilisticScorer) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) +} +#[no_mangle] +pub(crate) extern "C" fn ProbabilisticScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeProbabilisticScorer) }) +} +#[no_mangle] +/// Read a ProbabilisticScorer from a byte array, created by ProbabilisticScorer_write +pub extern "C" fn ProbabilisticScorer_read(ser: crate::c_types::u8slice, arg_a: crate::lightning::routing::scoring::ProbabilisticScoringParameters, arg_b: &crate::lightning::routing::network_graph::NetworkGraph) -> crate::c_types::derived::CResult_ProbabilisticScorerDecodeErrorZ { + let arg_a_conv = *unsafe { Box::from_raw(arg_a.take_inner()) }; + let arg_b_conv = arg_b.get_native_ref(); + let arg_conv = (arg_a_conv, arg_b_conv); + let res: Result, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv); + 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() }; + local_res +} mod time { -use std::str::FromStr; -use std::ffi::c_void; +use alloc::str::FromStr; +use core::ffi::c_void; use core::convert::Infallible; use bitcoin::hashes::Hash; use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; }