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 //! [`ProbabilisticScorer`] may be given to [`find_route`] to score payment channels during path
12 //! finding when a custom [`Score`] implementation is not needed.
17 //! # extern crate bitcoin;
19 //! # use lightning::routing::gossip::NetworkGraph;
20 //! # use lightning::routing::router::{RouteParameters, find_route};
21 //! # use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
22 //! # use lightning::chain::keysinterface::{KeysManager, KeysInterface};
23 //! # use lightning::util::logger::{Logger, Record};
24 //! # use bitcoin::secp256k1::PublicKey;
26 //! # struct FakeLogger {};
27 //! # impl Logger for FakeLogger {
28 //! # fn log(&self, record: &Record) { unimplemented!() }
30 //! # fn find_scored_route(payer: PublicKey, route_params: RouteParameters, network_graph: NetworkGraph<&FakeLogger>) {
31 //! # let logger = FakeLogger {};
33 //! // Use the default channel penalties.
34 //! let params = ProbabilisticScoringParameters::default();
35 //! let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
37 //! // Or use custom channel penalties.
38 //! let params = ProbabilisticScoringParameters {
39 //! liquidity_penalty_multiplier_msat: 2 * 1000,
40 //! ..ProbabilisticScoringParameters::default()
42 //! let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
43 //! # let random_seed_bytes = [42u8; 32];
45 //! let route = find_route(&payer, &route_params, &network_graph.read_only(), None, &logger, &scorer, &random_seed_bytes);
51 //! Persisting when built with feature `no-std` and restoring without it, or vice versa, uses
52 //! different types and thus is undefined.
54 //! [`find_route`]: crate::routing::router::find_route
56 use alloc::str::FromStr;
57 use core::ffi::c_void;
58 use core::convert::Infallible;
59 use bitcoin::hashes::Hash;
60 use crate::c_types::*;
61 #[cfg(feature="no-std")]
62 use alloc::{vec::Vec, boxed::Box};
64 /// An interface used to score payment channels for path finding.
66 ///\tScoring is in terms of fees willing to be paid in order to avoid routing through a channel.
69 /// An opaque pointer which is passed to your function implementations as an argument.
70 /// This has no meaning in the LDK, and can be NULL or any other value.
71 pub this_arg: *mut c_void,
72 /// Returns the fee in msats willing to be paid to avoid routing `send_amt_msat` through the
73 /// given channel in the direction from `source` to `target`.
75 /// The channel's capacity (less any other MPP parts that are also being considered for use in
76 /// the same payment) is given by `capacity_msat`. It may be determined from various sources
77 /// such as a chain data, network gossip, or invoice hints. For invoice hints, a capacity near
78 /// [`u64::max_value`] is given to indicate sufficient capacity for the invoice's full amount.
79 /// Thus, implementations should be overflow-safe.
81 pub channel_penalty_msat: extern "C" fn (this_arg: *const c_void, short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, usage: crate::lightning::routing::scoring::ChannelUsage) -> u64,
82 /// Handles updating channel penalties after failing to route through a channel.
83 pub payment_path_failed: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ, short_channel_id: u64),
84 /// Handles updating channel penalties after successfully routing along a path.
85 pub payment_path_successful: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ),
86 /// Serialize the object into a byte array
87 pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
88 /// Frees any resources associated with this object given its this_arg pointer.
89 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
90 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
92 unsafe impl Send for Score {}
93 unsafe impl Sync for Score {}
95 pub(crate) extern "C" fn Score_clone_fields(orig: &Score) -> Score {
97 this_arg: orig.this_arg,
98 channel_penalty_msat: Clone::clone(&orig.channel_penalty_msat),
99 payment_path_failed: Clone::clone(&orig.payment_path_failed),
100 payment_path_successful: Clone::clone(&orig.payment_path_successful),
101 write: Clone::clone(&orig.write),
102 free: Clone::clone(&orig.free),
105 impl lightning::util::ser::Writeable for Score {
106 fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
107 let vec = (self.write)(self.this_arg);
108 w.write_all(vec.as_slice())
112 use lightning::routing::scoring::Score as rustScore;
113 impl rustScore for Score {
114 fn channel_penalty_msat(&self, mut short_channel_id: u64, mut source: &lightning::routing::gossip::NodeId, mut target: &lightning::routing::gossip::NodeId, mut usage: lightning::routing::scoring::ChannelUsage) -> u64 {
115 let mut ret = (self.channel_penalty_msat)(self.this_arg, short_channel_id, &crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((source as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false }, &crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((target as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false }, crate::lightning::routing::scoring::ChannelUsage { inner: ObjOps::heap_alloc(usage), is_owned: true });
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)
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())
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 core::ops::Deref for Score {
132 fn deref(&self) -> &Self {
136 /// Calls the free function if one is set
138 pub extern "C" fn Score_free(this_ptr: Score) { }
139 impl Drop for Score {
141 if let Some(f) = self.free {
146 /// A scorer that is accessed under a lock.
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.
153 /// [`find_route`]: crate::routing::router::find_route
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.
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)>,
166 unsafe impl Send for LockableScore {}
167 unsafe impl Sync for LockableScore {}
169 pub(crate) extern "C" fn LockableScore_clone_fields(orig: &LockableScore) -> LockableScore {
171 this_arg: orig.this_arg,
172 lock: Clone::clone(&orig.lock),
173 free: Clone::clone(&orig.free),
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);
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 core::ops::Deref for LockableScore {
190 fn deref(&self) -> &Self {
194 /// Calls the free function if one is set
196 pub extern "C" fn LockableScore_free(this_ptr: LockableScore) { }
197 impl Drop for LockableScore {
199 if let Some(f) = self.free {
204 /// Refers to a scorer that is accessible under lock and also writeable to disk
206 /// We need this trait to be able to pass in a scorer to `lightning-background-processor` that will enable us to
207 /// use the Persister to persist it.
209 pub struct WriteableScore {
210 /// An opaque pointer which is passed to your function implementations as an argument.
211 /// This has no meaning in the LDK, and can be NULL or any other value.
212 pub this_arg: *mut c_void,
213 /// Implementation of LockableScore for this object.
214 pub LockableScore: crate::lightning::routing::scoring::LockableScore,
215 /// Serialize the object into a byte array
216 pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
217 /// Frees any resources associated with this object given its this_arg pointer.
218 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
219 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
221 unsafe impl Send for WriteableScore {}
222 unsafe impl Sync for WriteableScore {}
224 pub(crate) extern "C" fn WriteableScore_clone_fields(orig: &WriteableScore) -> WriteableScore {
226 this_arg: orig.this_arg,
227 LockableScore: crate::lightning::routing::scoring::LockableScore_clone_fields(&orig.LockableScore),
228 write: Clone::clone(&orig.write),
229 free: Clone::clone(&orig.free),
232 impl<'a> lightning::routing::scoring::LockableScore<'a> for WriteableScore {
233 type Locked = crate::lightning::routing::scoring::Score;
234 fn lock(&'a self) -> crate::lightning::routing::scoring::Score {
235 let mut ret = (self.LockableScore.lock)(self.LockableScore.this_arg);
239 impl lightning::util::ser::Writeable for WriteableScore {
240 fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
241 let vec = (self.write)(self.this_arg);
242 w.write_all(vec.as_slice())
246 use lightning::routing::scoring::WriteableScore as rustWriteableScore;
247 impl<'a> rustWriteableScore<'a> for WriteableScore {
250 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
251 // directly as a Deref trait in higher-level structs:
252 impl core::ops::Deref for WriteableScore {
254 fn deref(&self) -> &Self {
258 /// Calls the free function if one is set
260 pub extern "C" fn WriteableScore_free(this_ptr: WriteableScore) { }
261 impl Drop for WriteableScore {
263 if let Some(f) = self.free {
269 use lightning::routing::scoring::MultiThreadedLockableScore as nativeMultiThreadedLockableScoreImport;
270 pub(crate) type nativeMultiThreadedLockableScore = nativeMultiThreadedLockableScoreImport<crate::lightning::routing::scoring::Score>;
272 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
275 pub struct MultiThreadedLockableScore {
276 /// A pointer to the opaque Rust object.
278 /// Nearly everywhere, inner must be non-null, however in places where
279 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
280 pub inner: *mut nativeMultiThreadedLockableScore,
281 /// Indicates that this is the only struct which contains the same pointer.
283 /// Rust functions which take ownership of an object provided via an argument require
284 /// this to be true and invalidate the object pointed to by inner.
288 impl Drop for MultiThreadedLockableScore {
290 if self.is_owned && !<*mut nativeMultiThreadedLockableScore>::is_null(self.inner) {
291 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
295 /// Frees any resources used by the MultiThreadedLockableScore, if is_owned is set and inner is non-NULL.
297 pub extern "C" fn MultiThreadedLockableScore_free(this_obj: MultiThreadedLockableScore) { }
299 /// Used only if an object of this type is returned as a trait impl by a method
300 pub(crate) extern "C" fn MultiThreadedLockableScore_free_void(this_ptr: *mut c_void) {
301 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMultiThreadedLockableScore); }
304 impl MultiThreadedLockableScore {
305 pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedLockableScore {
306 unsafe { &*ObjOps::untweak_ptr(self.inner) }
308 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedLockableScore {
309 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
311 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
312 pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedLockableScore {
313 assert!(self.is_owned);
314 let ret = ObjOps::untweak_ptr(self.inner);
315 self.inner = core::ptr::null_mut();
319 /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
322 pub extern "C" fn MultiThreadedLockableScore_new(mut score: crate::lightning::routing::scoring::Score) -> crate::lightning::routing::scoring::MultiThreadedLockableScore {
323 let mut ret = lightning::routing::scoring::MultiThreadedLockableScore::new(score);
324 crate::lightning::routing::scoring::MultiThreadedLockableScore { inner: ObjOps::heap_alloc(ret), is_owned: true }
328 use lightning::routing::scoring::ChannelUsage as nativeChannelUsageImport;
329 pub(crate) type nativeChannelUsage = nativeChannelUsageImport;
331 /// Proposed use of a channel passed as a parameter to [`Score::channel_penalty_msat`].
334 pub struct ChannelUsage {
335 /// A pointer to the opaque Rust object.
337 /// Nearly everywhere, inner must be non-null, however in places where
338 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
339 pub inner: *mut nativeChannelUsage,
340 /// Indicates that this is the only struct which contains the same pointer.
342 /// Rust functions which take ownership of an object provided via an argument require
343 /// this to be true and invalidate the object pointed to by inner.
347 impl Drop for ChannelUsage {
349 if self.is_owned && !<*mut nativeChannelUsage>::is_null(self.inner) {
350 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
354 /// Frees any resources used by the ChannelUsage, if is_owned is set and inner is non-NULL.
356 pub extern "C" fn ChannelUsage_free(this_obj: ChannelUsage) { }
358 /// Used only if an object of this type is returned as a trait impl by a method
359 pub(crate) extern "C" fn ChannelUsage_free_void(this_ptr: *mut c_void) {
360 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelUsage); }
364 pub(crate) fn get_native_ref(&self) -> &'static nativeChannelUsage {
365 unsafe { &*ObjOps::untweak_ptr(self.inner) }
367 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelUsage {
368 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
370 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
371 pub(crate) fn take_inner(mut self) -> *mut nativeChannelUsage {
372 assert!(self.is_owned);
373 let ret = ObjOps::untweak_ptr(self.inner);
374 self.inner = core::ptr::null_mut();
378 /// The amount to send through the channel, denominated in millisatoshis.
380 pub extern "C" fn ChannelUsage_get_amount_msat(this_ptr: &ChannelUsage) -> u64 {
381 let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_msat;
384 /// The amount to send through the channel, denominated in millisatoshis.
386 pub extern "C" fn ChannelUsage_set_amount_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
387 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_msat = val;
389 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
390 /// as part of a multi-path payment.
392 pub extern "C" fn ChannelUsage_get_inflight_htlc_msat(this_ptr: &ChannelUsage) -> u64 {
393 let mut inner_val = &mut this_ptr.get_native_mut_ref().inflight_htlc_msat;
396 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
397 /// as part of a multi-path payment.
399 pub extern "C" fn ChannelUsage_set_inflight_htlc_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
400 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inflight_htlc_msat = val;
402 /// The effective capacity of the channel.
404 pub extern "C" fn ChannelUsage_get_effective_capacity(this_ptr: &ChannelUsage) -> crate::lightning::routing::gossip::EffectiveCapacity {
405 let mut inner_val = &mut this_ptr.get_native_mut_ref().effective_capacity;
406 crate::lightning::routing::gossip::EffectiveCapacity::from_native(inner_val)
408 /// The effective capacity of the channel.
410 pub extern "C" fn ChannelUsage_set_effective_capacity(this_ptr: &mut ChannelUsage, mut val: crate::lightning::routing::gossip::EffectiveCapacity) {
411 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.effective_capacity = val.into_native();
413 /// Constructs a new ChannelUsage given each field
416 pub extern "C" fn ChannelUsage_new(mut amount_msat_arg: u64, mut inflight_htlc_msat_arg: u64, mut effective_capacity_arg: crate::lightning::routing::gossip::EffectiveCapacity) -> ChannelUsage {
417 ChannelUsage { inner: ObjOps::heap_alloc(nativeChannelUsage {
418 amount_msat: amount_msat_arg,
419 inflight_htlc_msat: inflight_htlc_msat_arg,
420 effective_capacity: effective_capacity_arg.into_native(),
423 impl Clone for ChannelUsage {
424 fn clone(&self) -> Self {
426 inner: if <*mut nativeChannelUsage>::is_null(self.inner) { core::ptr::null_mut() } else {
427 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
433 /// Used only if an object of this type is returned as a trait impl by a method
434 pub(crate) extern "C" fn ChannelUsage_clone_void(this_ptr: *const c_void) -> *mut c_void {
435 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelUsage)).clone() })) as *mut c_void
438 /// Creates a copy of the ChannelUsage
439 pub extern "C" fn ChannelUsage_clone(orig: &ChannelUsage) -> ChannelUsage {
443 use lightning::routing::scoring::FixedPenaltyScorer as nativeFixedPenaltyScorerImport;
444 pub(crate) type nativeFixedPenaltyScorer = nativeFixedPenaltyScorerImport;
446 /// [`Score`] implementation that uses a fixed penalty.
449 pub struct FixedPenaltyScorer {
450 /// A pointer to the opaque Rust object.
452 /// Nearly everywhere, inner must be non-null, however in places where
453 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
454 pub inner: *mut nativeFixedPenaltyScorer,
455 /// Indicates that this is the only struct which contains the same pointer.
457 /// Rust functions which take ownership of an object provided via an argument require
458 /// this to be true and invalidate the object pointed to by inner.
462 impl Drop for FixedPenaltyScorer {
464 if self.is_owned && !<*mut nativeFixedPenaltyScorer>::is_null(self.inner) {
465 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
469 /// Frees any resources used by the FixedPenaltyScorer, if is_owned is set and inner is non-NULL.
471 pub extern "C" fn FixedPenaltyScorer_free(this_obj: FixedPenaltyScorer) { }
473 /// Used only if an object of this type is returned as a trait impl by a method
474 pub(crate) extern "C" fn FixedPenaltyScorer_free_void(this_ptr: *mut c_void) {
475 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeFixedPenaltyScorer); }
478 impl FixedPenaltyScorer {
479 pub(crate) fn get_native_ref(&self) -> &'static nativeFixedPenaltyScorer {
480 unsafe { &*ObjOps::untweak_ptr(self.inner) }
482 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFixedPenaltyScorer {
483 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
485 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
486 pub(crate) fn take_inner(mut self) -> *mut nativeFixedPenaltyScorer {
487 assert!(self.is_owned);
488 let ret = ObjOps::untweak_ptr(self.inner);
489 self.inner = core::ptr::null_mut();
493 impl Clone for FixedPenaltyScorer {
494 fn clone(&self) -> Self {
496 inner: if <*mut nativeFixedPenaltyScorer>::is_null(self.inner) { core::ptr::null_mut() } else {
497 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
503 /// Used only if an object of this type is returned as a trait impl by a method
504 pub(crate) extern "C" fn FixedPenaltyScorer_clone_void(this_ptr: *const c_void) -> *mut c_void {
505 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFixedPenaltyScorer)).clone() })) as *mut c_void
508 /// Creates a copy of the FixedPenaltyScorer
509 pub extern "C" fn FixedPenaltyScorer_clone(orig: &FixedPenaltyScorer) -> FixedPenaltyScorer {
512 /// Creates a new scorer using `penalty_msat`.
515 pub extern "C" fn FixedPenaltyScorer_with_penalty(mut penalty_msat: u64) -> crate::lightning::routing::scoring::FixedPenaltyScorer {
516 let mut ret = lightning::routing::scoring::FixedPenaltyScorer::with_penalty(penalty_msat);
517 crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
520 impl From<nativeFixedPenaltyScorer> for crate::lightning::routing::scoring::Score {
521 fn from(obj: nativeFixedPenaltyScorer) -> Self {
522 let mut rust_obj = FixedPenaltyScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
523 let mut ret = FixedPenaltyScorer_as_Score(&rust_obj);
524 // 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
525 rust_obj.inner = core::ptr::null_mut();
526 ret.free = Some(FixedPenaltyScorer_free_void);
530 /// Constructs a new Score which calls the relevant methods on this_arg.
531 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
533 pub extern "C" fn FixedPenaltyScorer_as_Score(this_arg: &FixedPenaltyScorer) -> crate::lightning::routing::scoring::Score {
534 crate::lightning::routing::scoring::Score {
535 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
537 channel_penalty_msat: FixedPenaltyScorer_Score_channel_penalty_msat,
538 payment_path_failed: FixedPenaltyScorer_Score_payment_path_failed,
539 payment_path_successful: FixedPenaltyScorer_Score_payment_path_successful,
540 write: FixedPenaltyScorer_write_void,
545 extern "C" fn FixedPenaltyScorer_Score_channel_penalty_msat(this_arg: *const c_void, unused_0: u64, unused_1: &crate::lightning::routing::gossip::NodeId, unused_2: &crate::lightning::routing::gossip::NodeId, unused_3: crate::lightning::routing::scoring::ChannelUsage) -> u64 {
546 let mut ret = <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, unused_0, unused_1.get_native_ref(), unused_2.get_native_ref(), *unsafe { Box::from_raw(unused_3.take_inner()) });
549 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) {
550 let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
551 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..], _short_channel_id)
553 extern "C" fn FixedPenaltyScorer_Score_payment_path_successful(this_arg: *mut c_void, mut _path: crate::c_types::derived::CVec_RouteHopZ) {
554 let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
555 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..])
559 /// Serialize the FixedPenaltyScorer object into a byte array which can be read by FixedPenaltyScorer_read
560 pub extern "C" fn FixedPenaltyScorer_write(obj: &crate::lightning::routing::scoring::FixedPenaltyScorer) -> crate::c_types::derived::CVec_u8Z {
561 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
564 pub(crate) extern "C" fn FixedPenaltyScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
565 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFixedPenaltyScorer) })
568 /// Read a FixedPenaltyScorer from a byte array, created by FixedPenaltyScorer_write
569 pub extern "C" fn FixedPenaltyScorer_read(ser: crate::c_types::u8slice, arg: u64) -> crate::c_types::derived::CResult_FixedPenaltyScorerDecodeErrorZ {
571 let res: Result<lightning::routing::scoring::FixedPenaltyScorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
572 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() };
576 use lightning::routing::scoring::ProbabilisticScorer as nativeProbabilisticScorerImport;
577 pub(crate) type nativeProbabilisticScorer = nativeProbabilisticScorerImport<&'static lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger>;
579 /// [`Score`] implementation using channel success probability distributions.
581 /// Based on *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
582 /// and Stefan Richter [[1]]. Given the uncertainty of channel liquidity balances, probability
583 /// distributions are defined based on knowledge learned from successful and unsuccessful attempts.
584 /// Then the negative `log10` of the success probability is used to determine the cost of routing a
585 /// specific HTLC amount through a channel.
587 /// Knowledge about channel liquidity balances takes the form of upper and lower bounds on the
588 /// possible liquidity. Certainty of the bounds is decreased over time using a decay function. See
589 /// [`ProbabilisticScoringParameters`] for details.
591 /// Since the scorer aims to learn the current channel liquidity balances, it works best for nodes
592 /// with high payment volume or that actively probe the [`NetworkGraph`]. Nodes with low payment
593 /// volume are more likely to experience failed payment paths, which would need to be retried.
597 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
600 /// [1]: https://arxiv.org/abs/2107.05322
603 pub struct ProbabilisticScorer {
604 /// A pointer to the opaque Rust object.
606 /// Nearly everywhere, inner must be non-null, however in places where
607 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
608 pub inner: *mut nativeProbabilisticScorer,
609 /// Indicates that this is the only struct which contains the same pointer.
611 /// Rust functions which take ownership of an object provided via an argument require
612 /// this to be true and invalidate the object pointed to by inner.
616 impl Drop for ProbabilisticScorer {
618 if self.is_owned && !<*mut nativeProbabilisticScorer>::is_null(self.inner) {
619 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
623 /// Frees any resources used by the ProbabilisticScorer, if is_owned is set and inner is non-NULL.
625 pub extern "C" fn ProbabilisticScorer_free(this_obj: ProbabilisticScorer) { }
627 /// Used only if an object of this type is returned as a trait impl by a method
628 pub(crate) extern "C" fn ProbabilisticScorer_free_void(this_ptr: *mut c_void) {
629 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScorer); }
632 impl ProbabilisticScorer {
633 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScorer {
634 unsafe { &*ObjOps::untweak_ptr(self.inner) }
636 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScorer {
637 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
639 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
640 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScorer {
641 assert!(self.is_owned);
642 let ret = ObjOps::untweak_ptr(self.inner);
643 self.inner = core::ptr::null_mut();
648 use lightning::routing::scoring::ProbabilisticScoringParameters as nativeProbabilisticScoringParametersImport;
649 pub(crate) type nativeProbabilisticScoringParameters = nativeProbabilisticScoringParametersImport;
651 /// Parameters for configuring [`ProbabilisticScorer`].
653 /// Used to configure base, liquidity, and amount penalties, the sum of which comprises the channel
654 /// penalty (i.e., the amount in msats willing to be paid to avoid routing through the channel).
657 pub struct ProbabilisticScoringParameters {
658 /// A pointer to the opaque Rust object.
660 /// Nearly everywhere, inner must be non-null, however in places where
661 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
662 pub inner: *mut nativeProbabilisticScoringParameters,
663 /// Indicates that this is the only struct which contains the same pointer.
665 /// Rust functions which take ownership of an object provided via an argument require
666 /// this to be true and invalidate the object pointed to by inner.
670 impl Drop for ProbabilisticScoringParameters {
672 if self.is_owned && !<*mut nativeProbabilisticScoringParameters>::is_null(self.inner) {
673 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
677 /// Frees any resources used by the ProbabilisticScoringParameters, if is_owned is set and inner is non-NULL.
679 pub extern "C" fn ProbabilisticScoringParameters_free(this_obj: ProbabilisticScoringParameters) { }
681 /// Used only if an object of this type is returned as a trait impl by a method
682 pub(crate) extern "C" fn ProbabilisticScoringParameters_free_void(this_ptr: *mut c_void) {
683 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScoringParameters); }
686 impl ProbabilisticScoringParameters {
687 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringParameters {
688 unsafe { &*ObjOps::untweak_ptr(self.inner) }
690 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringParameters {
691 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
693 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
694 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringParameters {
695 assert!(self.is_owned);
696 let ret = ObjOps::untweak_ptr(self.inner);
697 self.inner = core::ptr::null_mut();
701 /// A fixed penalty in msats to apply to each channel.
703 /// Default value: 500 msat
705 pub extern "C" fn ProbabilisticScoringParameters_get_base_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
706 let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
709 /// A fixed penalty in msats to apply to each channel.
711 /// Default value: 500 msat
713 pub extern "C" fn ProbabilisticScoringParameters_set_base_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
714 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
716 /// A multiplier used in conjunction with the negative `log10` of the channel's success
717 /// probability for a payment to determine the liquidity penalty.
719 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
720 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
721 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
722 /// lower bounding the success probability to `0.01`) when the amount falls within the
723 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
724 /// result in a `u64::max_value` penalty, however.
726 /// Default value: 40,000 msat
728 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
730 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
731 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_multiplier_msat;
734 /// A multiplier used in conjunction with the negative `log10` of the channel's success
735 /// probability for a payment to determine the liquidity penalty.
737 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
738 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
739 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
740 /// lower bounding the success probability to `0.01`) when the amount falls within the
741 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
742 /// result in a `u64::max_value` penalty, however.
744 /// Default value: 40,000 msat
746 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
748 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
749 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_multiplier_msat = val;
751 /// The time required to elapse before any knowledge learned about channel liquidity balances is
754 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
755 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
756 /// the certainty of the channel liquidity balance.
758 /// Default value: 1 hour
762 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
763 /// liquidity knowledge will never decay except when the bounds cross.
765 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_offset_half_life(this_ptr: &ProbabilisticScoringParameters) -> u64 {
766 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_offset_half_life;
769 /// The time required to elapse before any knowledge learned about channel liquidity balances is
772 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
773 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
774 /// the certainty of the channel liquidity balance.
776 /// Default value: 1 hour
780 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
781 /// liquidity knowledge will never decay except when the bounds cross.
783 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_offset_half_life(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
784 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_offset_half_life = core::time::Duration::from_secs(val);
786 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
787 /// channel's success probability for the payment to determine the amount penalty.
789 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
790 /// fees plus penalty) for large payments. The penalty is computed as the product of this
791 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
792 /// success probability.
794 /// `-log10(success_probability) * amount_penalty_multiplier_msat * amount_msat / 2^20`
796 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
797 /// the amount will result in a penalty of the multiplier. And, as the success probability
798 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
799 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
802 /// Default value: 256 msat
804 pub extern "C" fn ProbabilisticScoringParameters_get_amount_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
805 let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_penalty_multiplier_msat;
808 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
809 /// channel's success probability for the payment to determine the amount penalty.
811 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
812 /// fees plus penalty) for large payments. The penalty is computed as the product of this
813 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
814 /// success probability.
816 /// `-log10(success_probability) * amount_penalty_multiplier_msat * amount_msat / 2^20`
818 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
819 /// the amount will result in a penalty of the multiplier. And, as the success probability
820 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
821 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
824 /// Default value: 256 msat
826 pub extern "C" fn ProbabilisticScoringParameters_set_amount_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
827 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_penalty_multiplier_msat = val;
829 /// Constructs a new ProbabilisticScoringParameters given each field
832 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 {
833 ProbabilisticScoringParameters { inner: ObjOps::heap_alloc(nativeProbabilisticScoringParameters {
834 base_penalty_msat: base_penalty_msat_arg,
835 liquidity_penalty_multiplier_msat: liquidity_penalty_multiplier_msat_arg,
836 liquidity_offset_half_life: core::time::Duration::from_secs(liquidity_offset_half_life_arg),
837 amount_penalty_multiplier_msat: amount_penalty_multiplier_msat_arg,
840 impl Clone for ProbabilisticScoringParameters {
841 fn clone(&self) -> Self {
843 inner: if <*mut nativeProbabilisticScoringParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
844 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
850 /// Used only if an object of this type is returned as a trait impl by a method
851 pub(crate) extern "C" fn ProbabilisticScoringParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
852 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeProbabilisticScoringParameters)).clone() })) as *mut c_void
855 /// Creates a copy of the ProbabilisticScoringParameters
856 pub extern "C" fn ProbabilisticScoringParameters_clone(orig: &ProbabilisticScoringParameters) -> ProbabilisticScoringParameters {
859 /// Creates a new scorer using the given scoring parameters for sending payments from a node
860 /// through a network graph.
863 pub extern "C" fn ProbabilisticScorer_new(mut params: crate::lightning::routing::scoring::ProbabilisticScoringParameters, network_graph: &crate::lightning::routing::gossip::NetworkGraph, mut logger: crate::lightning::util::logger::Logger) -> crate::lightning::routing::scoring::ProbabilisticScorer {
864 let mut ret = lightning::routing::scoring::ProbabilisticScorer::new(*unsafe { Box::from_raw(params.take_inner()) }, network_graph.get_native_ref(), logger);
865 crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
868 /// Dump the contents of this scorer into the configured logger.
870 /// Note that this writes roughly one line per channel for which we have a liquidity estimate,
871 /// which may be a substantial amount of log output.
873 pub extern "C" fn ProbabilisticScorer_debug_log_liquidity_stats(this_arg: &crate::lightning::routing::scoring::ProbabilisticScorer) {
874 unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.debug_log_liquidity_stats()
877 /// Creates a "default" ProbabilisticScoringParameters. See struct and individual field documentaiton for details on which values are used.
880 pub extern "C" fn ProbabilisticScoringParameters_default() -> ProbabilisticScoringParameters {
881 ProbabilisticScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
883 impl From<nativeProbabilisticScorer> for crate::lightning::routing::scoring::Score {
884 fn from(obj: nativeProbabilisticScorer) -> Self {
885 let mut rust_obj = ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
886 let mut ret = ProbabilisticScorer_as_Score(&rust_obj);
887 // 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
888 rust_obj.inner = core::ptr::null_mut();
889 ret.free = Some(ProbabilisticScorer_free_void);
893 /// Constructs a new Score which calls the relevant methods on this_arg.
894 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
896 pub extern "C" fn ProbabilisticScorer_as_Score(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::Score {
897 crate::lightning::routing::scoring::Score {
898 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
900 channel_penalty_msat: ProbabilisticScorer_Score_channel_penalty_msat,
901 payment_path_failed: ProbabilisticScorer_Score_payment_path_failed,
902 payment_path_successful: ProbabilisticScorer_Score_payment_path_successful,
903 write: ProbabilisticScorer_write_void,
908 extern "C" fn ProbabilisticScorer_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, mut usage: crate::lightning::routing::scoring::ChannelUsage) -> u64 {
909 let mut ret = <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, short_channel_id, source.get_native_ref(), target.get_native_ref(), *unsafe { Box::from_raw(usage.take_inner()) });
912 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) {
913 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
914 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..], short_channel_id)
916 extern "C" fn ProbabilisticScorer_Score_payment_path_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
917 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
918 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..])
923 use alloc::str::FromStr;
924 use core::ffi::c_void;
925 use core::convert::Infallible;
926 use bitcoin::hashes::Hash;
927 use crate::c_types::*;
928 #[cfg(feature="no-std")]
929 use alloc::{vec::Vec, boxed::Box};
933 /// Serialize the ProbabilisticScorer object into a byte array which can be read by ProbabilisticScorer_read
934 pub extern "C" fn ProbabilisticScorer_write(obj: &crate::lightning::routing::scoring::ProbabilisticScorer) -> crate::c_types::derived::CVec_u8Z {
935 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
938 pub(crate) extern "C" fn ProbabilisticScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
939 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeProbabilisticScorer) })
942 /// Read a ProbabilisticScorer from a byte array, created by ProbabilisticScorer_write
943 pub extern "C" fn ProbabilisticScorer_read(ser: crate::c_types::u8slice, arg_a: crate::lightning::routing::scoring::ProbabilisticScoringParameters, arg_b: &crate::lightning::routing::gossip::NetworkGraph, arg_c: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_ProbabilisticScorerDecodeErrorZ {
944 let arg_a_conv = *unsafe { Box::from_raw(arg_a.take_inner()) };
945 let arg_b_conv = arg_b.get_native_ref();
946 let arg_c_conv = arg_c;
947 let arg_conv = (arg_a_conv, arg_b_conv, arg_c_conv);
948 let res: Result<lightning::routing::scoring::ProbabilisticScorer<&lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger>, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
949 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() };