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 //! This module contains an [`OutputSweeper`] utility that keeps track of
10 //! [`SpendableOutputDescriptor`]s, i.e., persists them in a given [`KVStore`] and regularly retries
13 use alloc::str::FromStr;
14 use alloc::string::String;
15 use core::ffi::c_void;
16 use core::convert::Infallible;
17 use bitcoin::hashes::Hash;
18 use crate::c_types::*;
19 #[cfg(feature="no-std")]
20 use alloc::{vec::Vec, boxed::Box};
23 use lightning::util::sweep::TrackedSpendableOutput as nativeTrackedSpendableOutputImport;
24 pub(crate) type nativeTrackedSpendableOutput = nativeTrackedSpendableOutputImport;
26 /// The state of a spendable output currently tracked by an [`OutputSweeper`].
29 pub struct TrackedSpendableOutput {
30 /// A pointer to the opaque Rust object.
32 /// Nearly everywhere, inner must be non-null, however in places where
33 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
34 pub inner: *mut nativeTrackedSpendableOutput,
35 /// Indicates that this is the only struct which contains the same pointer.
37 /// Rust functions which take ownership of an object provided via an argument require
38 /// this to be true and invalidate the object pointed to by inner.
42 impl Drop for TrackedSpendableOutput {
44 if self.is_owned && !<*mut nativeTrackedSpendableOutput>::is_null(self.inner) {
45 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
49 /// Frees any resources used by the TrackedSpendableOutput, if is_owned is set and inner is non-NULL.
51 pub extern "C" fn TrackedSpendableOutput_free(this_obj: TrackedSpendableOutput) { }
53 /// Used only if an object of this type is returned as a trait impl by a method
54 pub(crate) extern "C" fn TrackedSpendableOutput_free_void(this_ptr: *mut c_void) {
55 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeTrackedSpendableOutput) };
58 impl TrackedSpendableOutput {
59 pub(crate) fn get_native_ref(&self) -> &'static nativeTrackedSpendableOutput {
60 unsafe { &*ObjOps::untweak_ptr(self.inner) }
62 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeTrackedSpendableOutput {
63 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
65 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
66 pub(crate) fn take_inner(mut self) -> *mut nativeTrackedSpendableOutput {
67 assert!(self.is_owned);
68 let ret = ObjOps::untweak_ptr(self.inner);
69 self.inner = core::ptr::null_mut();
73 /// The tracked output descriptor.
75 pub extern "C" fn TrackedSpendableOutput_get_descriptor(this_ptr: &TrackedSpendableOutput) -> crate::lightning::sign::SpendableOutputDescriptor {
76 let mut inner_val = &mut this_ptr.get_native_mut_ref().descriptor;
77 crate::lightning::sign::SpendableOutputDescriptor::from_native(inner_val)
79 /// The tracked output descriptor.
81 pub extern "C" fn TrackedSpendableOutput_set_descriptor(this_ptr: &mut TrackedSpendableOutput, mut val: crate::lightning::sign::SpendableOutputDescriptor) {
82 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.descriptor = val.into_native();
84 /// The channel this output belongs to.
86 /// Will be `None` if no `channel_id` was given to [`OutputSweeper::track_spendable_outputs`]
88 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
90 pub extern "C" fn TrackedSpendableOutput_get_channel_id(this_ptr: &TrackedSpendableOutput) -> crate::lightning::ln::types::ChannelId {
91 let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id;
92 let mut local_inner_val = crate::lightning::ln::types::ChannelId { inner: unsafe { (if inner_val.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const lightning::ln::types::ChannelId<>) as *mut _ }, is_owned: false };
95 /// The channel this output belongs to.
97 /// Will be `None` if no `channel_id` was given to [`OutputSweeper::track_spendable_outputs`]
99 /// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
101 pub extern "C" fn TrackedSpendableOutput_set_channel_id(this_ptr: &mut TrackedSpendableOutput, mut val: crate::lightning::ln::types::ChannelId) {
102 let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) };
103 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_id = local_val;
105 /// The current status of the output spend.
107 pub extern "C" fn TrackedSpendableOutput_get_status(this_ptr: &TrackedSpendableOutput) -> crate::lightning::util::sweep::OutputSpendStatus {
108 let mut inner_val = &mut this_ptr.get_native_mut_ref().status;
109 crate::lightning::util::sweep::OutputSpendStatus::from_native(inner_val)
111 /// The current status of the output spend.
113 pub extern "C" fn TrackedSpendableOutput_set_status(this_ptr: &mut TrackedSpendableOutput, mut val: crate::lightning::util::sweep::OutputSpendStatus) {
114 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.status = val.into_native();
116 /// Constructs a new TrackedSpendableOutput given each field
118 /// Note that channel_id_arg (or a relevant inner pointer) may be NULL or all-0s to represent None
121 pub extern "C" fn TrackedSpendableOutput_new(mut descriptor_arg: crate::lightning::sign::SpendableOutputDescriptor, mut channel_id_arg: crate::lightning::ln::types::ChannelId, mut status_arg: crate::lightning::util::sweep::OutputSpendStatus) -> TrackedSpendableOutput {
122 let mut local_channel_id_arg = if channel_id_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(channel_id_arg.take_inner()) } }) };
123 TrackedSpendableOutput { inner: ObjOps::heap_alloc(nativeTrackedSpendableOutput {
124 descriptor: descriptor_arg.into_native(),
125 channel_id: local_channel_id_arg,
126 status: status_arg.into_native(),
129 impl Clone for TrackedSpendableOutput {
130 fn clone(&self) -> Self {
132 inner: if <*mut nativeTrackedSpendableOutput>::is_null(self.inner) { core::ptr::null_mut() } else {
133 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
139 /// Used only if an object of this type is returned as a trait impl by a method
140 pub(crate) extern "C" fn TrackedSpendableOutput_clone_void(this_ptr: *const c_void) -> *mut c_void {
141 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeTrackedSpendableOutput)).clone() })) as *mut c_void
144 /// Creates a copy of the TrackedSpendableOutput
145 pub extern "C" fn TrackedSpendableOutput_clone(orig: &TrackedSpendableOutput) -> TrackedSpendableOutput {
148 /// Get a string which allows debug introspection of a TrackedSpendableOutput object
149 pub extern "C" fn TrackedSpendableOutput_debug_str_void(o: *const c_void) -> Str {
150 alloc::format!("{:?}", unsafe { o as *const crate::lightning::util::sweep::TrackedSpendableOutput }).into()}
151 /// Checks if two TrackedSpendableOutputs contain equal inner contents.
152 /// This ignores pointers and is_owned flags and looks at the values in fields.
153 /// Two objects with NULL inner values will be considered "equal" here.
155 pub extern "C" fn TrackedSpendableOutput_eq(a: &TrackedSpendableOutput, b: &TrackedSpendableOutput) -> bool {
156 if a.inner == b.inner { return true; }
157 if a.inner.is_null() || b.inner.is_null() { return false; }
158 if a.get_native_ref() == b.get_native_ref() { true } else { false }
160 /// Returns whether the output is spent in the given transaction.
163 pub extern "C" fn TrackedSpendableOutput_is_spent_in(this_arg: &crate::lightning::util::sweep::TrackedSpendableOutput, mut tx: crate::c_types::Transaction) -> bool {
164 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_spent_in(&tx.into_bitcoin());
169 /// Serialize the TrackedSpendableOutput object into a byte array which can be read by TrackedSpendableOutput_read
170 pub extern "C" fn TrackedSpendableOutput_write(obj: &crate::lightning::util::sweep::TrackedSpendableOutput) -> crate::c_types::derived::CVec_u8Z {
171 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
174 pub(crate) extern "C" fn TrackedSpendableOutput_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
175 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeTrackedSpendableOutput) })
178 /// Read a TrackedSpendableOutput from a byte array, created by TrackedSpendableOutput_write
179 pub extern "C" fn TrackedSpendableOutput_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_TrackedSpendableOutputDecodeErrorZ {
180 let res: Result<lightning::util::sweep::TrackedSpendableOutput, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
181 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::util::sweep::TrackedSpendableOutput { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() };
184 /// The current status of the output spend.
188 pub enum OutputSpendStatus {
189 /// The output is tracked but an initial spending transaction hasn't been generated and
191 PendingInitialBroadcast {
192 /// The height at which we will first generate and broadcast a spending transaction.
193 delayed_until_height: crate::c_types::derived::COption_u32Z,
195 /// A transaction spending the output has been broadcasted but is pending its first confirmation on-chain.
196 PendingFirstConfirmation {
197 /// The hash of the chain tip when we first broadcast a transaction spending this output.
198 first_broadcast_hash: crate::c_types::ThirtyTwoBytes,
199 /// The best height when we last broadcast a transaction spending this output.
200 latest_broadcast_height: u32,
201 /// The transaction spending this output we last broadcasted.
202 latest_spending_tx: crate::c_types::Transaction,
204 /// A transaction spending the output has been confirmed on-chain but will be tracked until it
205 /// reaches [`ANTI_REORG_DELAY`] confirmations.
206 PendingThresholdConfirmations {
207 /// The hash of the chain tip when we first broadcast a transaction spending this output.
208 first_broadcast_hash: crate::c_types::ThirtyTwoBytes,
209 /// The best height when we last broadcast a transaction spending this output.
210 latest_broadcast_height: u32,
211 /// The transaction spending this output we saw confirmed on-chain.
212 latest_spending_tx: crate::c_types::Transaction,
213 /// The height at which the spending transaction was confirmed.
214 confirmation_height: u32,
215 /// The hash of the block in which the spending transaction was confirmed.
216 confirmation_hash: crate::c_types::ThirtyTwoBytes,
219 use lightning::util::sweep::OutputSpendStatus as OutputSpendStatusImport;
220 pub(crate) type nativeOutputSpendStatus = OutputSpendStatusImport;
222 impl OutputSpendStatus {
224 pub(crate) fn to_native(&self) -> nativeOutputSpendStatus {
226 OutputSpendStatus::PendingInitialBroadcast {ref delayed_until_height, } => {
227 let mut delayed_until_height_nonref = Clone::clone(delayed_until_height);
228 let mut local_delayed_until_height_nonref = if delayed_until_height_nonref.is_some() { Some( { delayed_until_height_nonref.take() }) } else { None };
229 nativeOutputSpendStatus::PendingInitialBroadcast {
230 delayed_until_height: local_delayed_until_height_nonref,
233 OutputSpendStatus::PendingFirstConfirmation {ref first_broadcast_hash, ref latest_broadcast_height, ref latest_spending_tx, } => {
234 let mut first_broadcast_hash_nonref = Clone::clone(first_broadcast_hash);
235 let mut latest_broadcast_height_nonref = Clone::clone(latest_broadcast_height);
236 let mut latest_spending_tx_nonref = Clone::clone(latest_spending_tx);
237 nativeOutputSpendStatus::PendingFirstConfirmation {
238 first_broadcast_hash: ::bitcoin::hash_types::BlockHash::from_slice(&first_broadcast_hash_nonref.data[..]).unwrap(),
239 latest_broadcast_height: latest_broadcast_height_nonref,
240 latest_spending_tx: latest_spending_tx_nonref.into_bitcoin(),
243 OutputSpendStatus::PendingThresholdConfirmations {ref first_broadcast_hash, ref latest_broadcast_height, ref latest_spending_tx, ref confirmation_height, ref confirmation_hash, } => {
244 let mut first_broadcast_hash_nonref = Clone::clone(first_broadcast_hash);
245 let mut latest_broadcast_height_nonref = Clone::clone(latest_broadcast_height);
246 let mut latest_spending_tx_nonref = Clone::clone(latest_spending_tx);
247 let mut confirmation_height_nonref = Clone::clone(confirmation_height);
248 let mut confirmation_hash_nonref = Clone::clone(confirmation_hash);
249 nativeOutputSpendStatus::PendingThresholdConfirmations {
250 first_broadcast_hash: ::bitcoin::hash_types::BlockHash::from_slice(&first_broadcast_hash_nonref.data[..]).unwrap(),
251 latest_broadcast_height: latest_broadcast_height_nonref,
252 latest_spending_tx: latest_spending_tx_nonref.into_bitcoin(),
253 confirmation_height: confirmation_height_nonref,
254 confirmation_hash: ::bitcoin::hash_types::BlockHash::from_slice(&confirmation_hash_nonref.data[..]).unwrap(),
260 pub(crate) fn into_native(self) -> nativeOutputSpendStatus {
262 OutputSpendStatus::PendingInitialBroadcast {mut delayed_until_height, } => {
263 let mut local_delayed_until_height = if delayed_until_height.is_some() { Some( { delayed_until_height.take() }) } else { None };
264 nativeOutputSpendStatus::PendingInitialBroadcast {
265 delayed_until_height: local_delayed_until_height,
268 OutputSpendStatus::PendingFirstConfirmation {mut first_broadcast_hash, mut latest_broadcast_height, mut latest_spending_tx, } => {
269 nativeOutputSpendStatus::PendingFirstConfirmation {
270 first_broadcast_hash: ::bitcoin::hash_types::BlockHash::from_slice(&first_broadcast_hash.data[..]).unwrap(),
271 latest_broadcast_height: latest_broadcast_height,
272 latest_spending_tx: latest_spending_tx.into_bitcoin(),
275 OutputSpendStatus::PendingThresholdConfirmations {mut first_broadcast_hash, mut latest_broadcast_height, mut latest_spending_tx, mut confirmation_height, mut confirmation_hash, } => {
276 nativeOutputSpendStatus::PendingThresholdConfirmations {
277 first_broadcast_hash: ::bitcoin::hash_types::BlockHash::from_slice(&first_broadcast_hash.data[..]).unwrap(),
278 latest_broadcast_height: latest_broadcast_height,
279 latest_spending_tx: latest_spending_tx.into_bitcoin(),
280 confirmation_height: confirmation_height,
281 confirmation_hash: ::bitcoin::hash_types::BlockHash::from_slice(&confirmation_hash.data[..]).unwrap(),
287 pub(crate) fn from_native(native: &OutputSpendStatusImport) -> Self {
288 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeOutputSpendStatus) };
290 nativeOutputSpendStatus::PendingInitialBroadcast {ref delayed_until_height, } => {
291 let mut delayed_until_height_nonref = Clone::clone(delayed_until_height);
292 let mut local_delayed_until_height_nonref = if delayed_until_height_nonref.is_none() { crate::c_types::derived::COption_u32Z::None } else { crate::c_types::derived::COption_u32Z::Some( { delayed_until_height_nonref.unwrap() }) };
293 OutputSpendStatus::PendingInitialBroadcast {
294 delayed_until_height: local_delayed_until_height_nonref,
297 nativeOutputSpendStatus::PendingFirstConfirmation {ref first_broadcast_hash, ref latest_broadcast_height, ref latest_spending_tx, } => {
298 let mut first_broadcast_hash_nonref = Clone::clone(first_broadcast_hash);
299 let mut latest_broadcast_height_nonref = Clone::clone(latest_broadcast_height);
300 let mut latest_spending_tx_nonref = Clone::clone(latest_spending_tx);
301 OutputSpendStatus::PendingFirstConfirmation {
302 first_broadcast_hash: crate::c_types::ThirtyTwoBytes { data: *first_broadcast_hash_nonref.as_ref() },
303 latest_broadcast_height: latest_broadcast_height_nonref,
304 latest_spending_tx: crate::c_types::Transaction::from_bitcoin(&latest_spending_tx_nonref),
307 nativeOutputSpendStatus::PendingThresholdConfirmations {ref first_broadcast_hash, ref latest_broadcast_height, ref latest_spending_tx, ref confirmation_height, ref confirmation_hash, } => {
308 let mut first_broadcast_hash_nonref = Clone::clone(first_broadcast_hash);
309 let mut latest_broadcast_height_nonref = Clone::clone(latest_broadcast_height);
310 let mut latest_spending_tx_nonref = Clone::clone(latest_spending_tx);
311 let mut confirmation_height_nonref = Clone::clone(confirmation_height);
312 let mut confirmation_hash_nonref = Clone::clone(confirmation_hash);
313 OutputSpendStatus::PendingThresholdConfirmations {
314 first_broadcast_hash: crate::c_types::ThirtyTwoBytes { data: *first_broadcast_hash_nonref.as_ref() },
315 latest_broadcast_height: latest_broadcast_height_nonref,
316 latest_spending_tx: crate::c_types::Transaction::from_bitcoin(&latest_spending_tx_nonref),
317 confirmation_height: confirmation_height_nonref,
318 confirmation_hash: crate::c_types::ThirtyTwoBytes { data: *confirmation_hash_nonref.as_ref() },
324 pub(crate) fn native_into(native: nativeOutputSpendStatus) -> Self {
326 nativeOutputSpendStatus::PendingInitialBroadcast {mut delayed_until_height, } => {
327 let mut local_delayed_until_height = if delayed_until_height.is_none() { crate::c_types::derived::COption_u32Z::None } else { crate::c_types::derived::COption_u32Z::Some( { delayed_until_height.unwrap() }) };
328 OutputSpendStatus::PendingInitialBroadcast {
329 delayed_until_height: local_delayed_until_height,
332 nativeOutputSpendStatus::PendingFirstConfirmation {mut first_broadcast_hash, mut latest_broadcast_height, mut latest_spending_tx, } => {
333 OutputSpendStatus::PendingFirstConfirmation {
334 first_broadcast_hash: crate::c_types::ThirtyTwoBytes { data: *first_broadcast_hash.as_ref() },
335 latest_broadcast_height: latest_broadcast_height,
336 latest_spending_tx: crate::c_types::Transaction::from_bitcoin(&latest_spending_tx),
339 nativeOutputSpendStatus::PendingThresholdConfirmations {mut first_broadcast_hash, mut latest_broadcast_height, mut latest_spending_tx, mut confirmation_height, mut confirmation_hash, } => {
340 OutputSpendStatus::PendingThresholdConfirmations {
341 first_broadcast_hash: crate::c_types::ThirtyTwoBytes { data: *first_broadcast_hash.as_ref() },
342 latest_broadcast_height: latest_broadcast_height,
343 latest_spending_tx: crate::c_types::Transaction::from_bitcoin(&latest_spending_tx),
344 confirmation_height: confirmation_height,
345 confirmation_hash: crate::c_types::ThirtyTwoBytes { data: *confirmation_hash.as_ref() },
351 /// Frees any resources used by the OutputSpendStatus
353 pub extern "C" fn OutputSpendStatus_free(this_ptr: OutputSpendStatus) { }
354 /// Creates a copy of the OutputSpendStatus
356 pub extern "C" fn OutputSpendStatus_clone(orig: &OutputSpendStatus) -> OutputSpendStatus {
360 /// Used only if an object of this type is returned as a trait impl by a method
361 pub(crate) extern "C" fn OutputSpendStatus_clone_void(this_ptr: *const c_void) -> *mut c_void {
362 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const OutputSpendStatus)).clone() })) as *mut c_void
365 /// Used only if an object of this type is returned as a trait impl by a method
366 pub(crate) extern "C" fn OutputSpendStatus_free_void(this_ptr: *mut c_void) {
367 let _ = unsafe { Box::from_raw(this_ptr as *mut OutputSpendStatus) };
370 /// Utility method to constructs a new PendingInitialBroadcast-variant OutputSpendStatus
371 pub extern "C" fn OutputSpendStatus_pending_initial_broadcast(delayed_until_height: crate::c_types::derived::COption_u32Z) -> OutputSpendStatus {
372 OutputSpendStatus::PendingInitialBroadcast {
373 delayed_until_height,
377 /// Utility method to constructs a new PendingFirstConfirmation-variant OutputSpendStatus
378 pub extern "C" fn OutputSpendStatus_pending_first_confirmation(first_broadcast_hash: crate::c_types::ThirtyTwoBytes, latest_broadcast_height: u32, latest_spending_tx: crate::c_types::Transaction) -> OutputSpendStatus {
379 OutputSpendStatus::PendingFirstConfirmation {
380 first_broadcast_hash,
381 latest_broadcast_height,
386 /// Utility method to constructs a new PendingThresholdConfirmations-variant OutputSpendStatus
387 pub extern "C" fn OutputSpendStatus_pending_threshold_confirmations(first_broadcast_hash: crate::c_types::ThirtyTwoBytes, latest_broadcast_height: u32, latest_spending_tx: crate::c_types::Transaction, confirmation_height: u32, confirmation_hash: crate::c_types::ThirtyTwoBytes) -> OutputSpendStatus {
388 OutputSpendStatus::PendingThresholdConfirmations {
389 first_broadcast_hash,
390 latest_broadcast_height,
396 /// Get a string which allows debug introspection of a OutputSpendStatus object
397 pub extern "C" fn OutputSpendStatus_debug_str_void(o: *const c_void) -> Str {
398 alloc::format!("{:?}", unsafe { o as *const crate::lightning::util::sweep::OutputSpendStatus }).into()}
399 /// Checks if two OutputSpendStatuss contain equal inner contents.
400 /// This ignores pointers and is_owned flags and looks at the values in fields.
402 pub extern "C" fn OutputSpendStatus_eq(a: &OutputSpendStatus, b: &OutputSpendStatus) -> bool {
403 if &a.to_native() == &b.to_native() { true } else { false }
406 /// Serialize the OutputSpendStatus object into a byte array which can be read by OutputSpendStatus_read
407 pub extern "C" fn OutputSpendStatus_write(obj: &crate::lightning::util::sweep::OutputSpendStatus) -> crate::c_types::derived::CVec_u8Z {
408 crate::c_types::serialize_obj(&unsafe { &*obj }.to_native())
411 pub(crate) extern "C" fn OutputSpendStatus_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
412 OutputSpendStatus_write(unsafe { &*(obj as *const OutputSpendStatus) })
415 /// Read a OutputSpendStatus from a byte array, created by OutputSpendStatus_write
416 pub extern "C" fn OutputSpendStatus_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_OutputSpendStatusDecodeErrorZ {
417 let res: Result<lightning::util::sweep::OutputSpendStatus, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
418 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::util::sweep::OutputSpendStatus::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() };
422 use lightning::util::sweep::OutputSweeper as nativeOutputSweeperImport;
423 pub(crate) type nativeOutputSweeper = nativeOutputSweeperImport<crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::sign::ChangeDestinationSource, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::chain::Filter, crate::lightning::util::persist::KVStore, crate::lightning::util::logger::Logger, crate::lightning::sign::OutputSpender, >;
425 /// A utility that keeps track of [`SpendableOutputDescriptor`]s, persists them in a given
426 /// [`KVStore`] and regularly retries sweeping them based on a callback given to the constructor
429 /// Users should call [`Self::track_spendable_outputs`] for any [`SpendableOutputDescriptor`]s received via [`Event::SpendableOutputs`].
431 /// This needs to be notified of chain state changes either via its [`Listen`] or [`Confirm`]
432 /// implementation and hence has to be connected with the utilized chain data sources.
434 /// If chain data is provided via the [`Confirm`] interface or via filtered blocks, users are
435 /// required to give their chain data sources (i.e., [`Filter`] implementation) to the respective
438 /// [`Event::SpendableOutputs`]: crate::events::Event::SpendableOutputs
441 pub struct OutputSweeper {
442 /// A pointer to the opaque Rust object.
444 /// Nearly everywhere, inner must be non-null, however in places where
445 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
446 pub inner: *mut nativeOutputSweeper,
447 /// Indicates that this is the only struct which contains the same pointer.
449 /// Rust functions which take ownership of an object provided via an argument require
450 /// this to be true and invalidate the object pointed to by inner.
454 impl Drop for OutputSweeper {
456 if self.is_owned && !<*mut nativeOutputSweeper>::is_null(self.inner) {
457 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
461 /// Frees any resources used by the OutputSweeper, if is_owned is set and inner is non-NULL.
463 pub extern "C" fn OutputSweeper_free(this_obj: OutputSweeper) { }
465 /// Used only if an object of this type is returned as a trait impl by a method
466 pub(crate) extern "C" fn OutputSweeper_free_void(this_ptr: *mut c_void) {
467 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeOutputSweeper) };
471 pub(crate) fn get_native_ref(&self) -> &'static nativeOutputSweeper {
472 unsafe { &*ObjOps::untweak_ptr(self.inner) }
474 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOutputSweeper {
475 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
477 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
478 pub(crate) fn take_inner(mut self) -> *mut nativeOutputSweeper {
479 assert!(self.is_owned);
480 let ret = ObjOps::untweak_ptr(self.inner);
481 self.inner = core::ptr::null_mut();
485 /// Constructs a new [`OutputSweeper`].
487 /// If chain data is provided via the [`Confirm`] interface or via filtered blocks, users also
488 /// need to register their [`Filter`] implementation via the given `chain_data_source`.
491 pub extern "C" fn OutputSweeper_new(mut best_block: crate::lightning::chain::BestBlock, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut chain_data_source: crate::c_types::derived::COption_FilterZ, mut output_spender: crate::lightning::sign::OutputSpender, mut change_destination_source: crate::lightning::sign::ChangeDestinationSource, mut kv_store: crate::lightning::util::persist::KVStore, mut logger: crate::lightning::util::logger::Logger) -> crate::lightning::util::sweep::OutputSweeper {
492 let mut local_chain_data_source = { /*chain_data_source*/ let chain_data_source_opt = chain_data_source; if chain_data_source_opt.is_none() { None } else { Some({ { { chain_data_source_opt.take() } }})} };
493 let mut ret = lightning::util::sweep::OutputSweeper::new(*unsafe { Box::from_raw(best_block.take_inner()) }, broadcaster, fee_estimator, local_chain_data_source, output_spender, change_destination_source, kv_store, logger);
494 crate::lightning::util::sweep::OutputSweeper { inner: ObjOps::heap_alloc(ret), is_owned: true }
497 /// Tells the sweeper to track the given outputs descriptors.
499 /// Usually, this should be called based on the values emitted by the
500 /// [`Event::SpendableOutputs`].
502 /// The given `exclude_static_outputs` flag controls whether the sweeper will filter out
503 /// [`SpendableOutputDescriptor::StaticOutput`]s, which may be handled directly by the on-chain
504 /// wallet implementation.
506 /// If `delay_until_height` is set, we will delay the spending until the respective block
507 /// height is reached. This can be used to batch spends, e.g., to reduce on-chain fees.
509 /// Returns `Err` on persistence failure, in which case the call may be safely retried.
511 /// [`Event::SpendableOutputs`]: crate::events::Event::SpendableOutputs
513 /// Note that channel_id (or a relevant inner pointer) may be NULL or all-0s to represent None
516 pub extern "C" fn OutputSweeper_track_spendable_outputs(this_arg: &crate::lightning::util::sweep::OutputSweeper, mut output_descriptors: crate::c_types::derived::CVec_SpendableOutputDescriptorZ, mut channel_id: crate::lightning::ln::types::ChannelId, mut exclude_static_outputs: bool, mut delay_until_height: crate::c_types::derived::COption_u32Z) -> crate::c_types::derived::CResult_NoneNoneZ {
517 let mut local_output_descriptors = Vec::new(); for mut item in output_descriptors.into_rust().drain(..) { local_output_descriptors.push( { item.into_native() }); };
518 let mut local_channel_id = if channel_id.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(channel_id.take_inner()) } }) };
519 let mut local_delay_until_height = if delay_until_height.is_some() { Some( { delay_until_height.take() }) } else { None };
520 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.track_spendable_outputs(local_output_descriptors, local_channel_id, exclude_static_outputs, local_delay_until_height);
521 let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
525 /// Returns a list of the currently tracked spendable outputs.
528 pub extern "C" fn OutputSweeper_tracked_spendable_outputs(this_arg: &crate::lightning::util::sweep::OutputSweeper) -> crate::c_types::derived::CVec_TrackedSpendableOutputZ {
529 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.tracked_spendable_outputs();
530 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::util::sweep::TrackedSpendableOutput { inner: ObjOps::heap_alloc(item), is_owned: true } }); };
534 /// Gets the latest best block which was connected either via the [`Listen`] or
535 /// [`Confirm`] interfaces.
538 pub extern "C" fn OutputSweeper_current_best_block(this_arg: &crate::lightning::util::sweep::OutputSweeper) -> crate::lightning::chain::BestBlock {
539 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.current_best_block();
540 crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
543 impl From<nativeOutputSweeper> for crate::lightning::chain::Listen {
544 fn from(obj: nativeOutputSweeper) -> Self {
545 let rust_obj = crate::lightning::util::sweep::OutputSweeper { inner: ObjOps::heap_alloc(obj), is_owned: true };
546 let mut ret = OutputSweeper_as_Listen(&rust_obj);
547 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
548 core::mem::forget(rust_obj);
549 ret.free = Some(OutputSweeper_free_void);
553 /// Constructs a new Listen which calls the relevant methods on this_arg.
554 /// This copies the `inner` pointer in this_arg and thus the returned Listen must be freed before this_arg is
556 pub extern "C" fn OutputSweeper_as_Listen(this_arg: &OutputSweeper) -> crate::lightning::chain::Listen {
557 crate::lightning::chain::Listen {
558 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
560 filtered_block_connected: OutputSweeper_Listen_filtered_block_connected,
561 block_connected: OutputSweeper_Listen_block_connected,
562 block_disconnected: OutputSweeper_Listen_block_disconnected,
566 extern "C" fn OutputSweeper_Listen_filtered_block_connected(this_arg: *const c_void, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32) {
567 let mut local_txdata = Vec::new(); for mut item in txdata.into_rust().drain(..) { local_txdata.push( { let (mut orig_txdata_0_0, mut orig_txdata_0_1) = item.to_rust(); let mut local_txdata_0 = (orig_txdata_0_0, orig_txdata_0_1.into_bitcoin()); local_txdata_0 }); };
568 <nativeOutputSweeper as lightning::chain::Listen>::filtered_block_connected(unsafe { &mut *(this_arg as *mut nativeOutputSweeper) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::<Vec<_>>()[..], height)
570 extern "C" fn OutputSweeper_Listen_block_connected(this_arg: *const c_void, mut block: crate::c_types::u8slice, mut height: u32) {
571 <nativeOutputSweeper as lightning::chain::Listen>::block_connected(unsafe { &mut *(this_arg as *mut nativeOutputSweeper) }, &::bitcoin::consensus::encode::deserialize(block.to_slice()).unwrap(), height)
573 extern "C" fn OutputSweeper_Listen_block_disconnected(this_arg: *const c_void, header: *const [u8; 80], mut height: u32) {
574 <nativeOutputSweeper as lightning::chain::Listen>::block_disconnected(unsafe { &mut *(this_arg as *mut nativeOutputSweeper) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height)
577 impl From<nativeOutputSweeper> for crate::lightning::chain::Confirm {
578 fn from(obj: nativeOutputSweeper) -> Self {
579 let rust_obj = crate::lightning::util::sweep::OutputSweeper { inner: ObjOps::heap_alloc(obj), is_owned: true };
580 let mut ret = OutputSweeper_as_Confirm(&rust_obj);
581 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
582 core::mem::forget(rust_obj);
583 ret.free = Some(OutputSweeper_free_void);
587 /// Constructs a new Confirm which calls the relevant methods on this_arg.
588 /// This copies the `inner` pointer in this_arg and thus the returned Confirm must be freed before this_arg is
590 pub extern "C" fn OutputSweeper_as_Confirm(this_arg: &OutputSweeper) -> crate::lightning::chain::Confirm {
591 crate::lightning::chain::Confirm {
592 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
594 transactions_confirmed: OutputSweeper_Confirm_transactions_confirmed,
595 transaction_unconfirmed: OutputSweeper_Confirm_transaction_unconfirmed,
596 best_block_updated: OutputSweeper_Confirm_best_block_updated,
597 get_relevant_txids: OutputSweeper_Confirm_get_relevant_txids,
601 extern "C" fn OutputSweeper_Confirm_transactions_confirmed(this_arg: *const c_void, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32) {
602 let mut local_txdata = Vec::new(); for mut item in txdata.into_rust().drain(..) { local_txdata.push( { let (mut orig_txdata_0_0, mut orig_txdata_0_1) = item.to_rust(); let mut local_txdata_0 = (orig_txdata_0_0, orig_txdata_0_1.into_bitcoin()); local_txdata_0 }); };
603 <nativeOutputSweeper as lightning::chain::Confirm>::transactions_confirmed(unsafe { &mut *(this_arg as *mut nativeOutputSweeper) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::<Vec<_>>()[..], height)
605 extern "C" fn OutputSweeper_Confirm_transaction_unconfirmed(this_arg: *const c_void, txid: *const [u8; 32]) {
606 <nativeOutputSweeper as lightning::chain::Confirm>::transaction_unconfirmed(unsafe { &mut *(this_arg as *mut nativeOutputSweeper) }, &::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap())
608 extern "C" fn OutputSweeper_Confirm_best_block_updated(this_arg: *const c_void, header: *const [u8; 80], mut height: u32) {
609 <nativeOutputSweeper as lightning::chain::Confirm>::best_block_updated(unsafe { &mut *(this_arg as *mut nativeOutputSweeper) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height)
612 extern "C" fn OutputSweeper_Confirm_get_relevant_txids(this_arg: *const c_void) -> crate::c_types::derived::CVec_C3Tuple_ThirtyTwoBytesu32COption_ThirtyTwoBytesZZZ {
613 let mut ret = <nativeOutputSweeper as lightning::chain::Confirm>::get_relevant_txids(unsafe { &mut *(this_arg as *mut nativeOutputSweeper) }, );
614 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = item; let mut local_orig_ret_0_2 = if orig_ret_0_2.is_none() { crate::c_types::derived::COption_ThirtyTwoBytesZ::None } else { crate::c_types::derived::COption_ThirtyTwoBytesZ::Some( { crate::c_types::ThirtyTwoBytes { data: *orig_ret_0_2.unwrap().as_ref() } }) }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: *orig_ret_0_0.as_ref() }, orig_ret_0_1, local_orig_ret_0_2).into(); local_ret_0 }); };
618 /// A `enum` signalling to the [`OutputSweeper`] that it should delay spending an output until a
619 /// future block height is reached.
623 pub enum SpendingDelay {
624 /// A relative delay indicating we shouldn't spend the output before `cur_height + num_blocks`
627 /// The number of blocks until we'll generate and broadcast the spending transaction.
630 /// An absolute delay indicating we shouldn't spend the output before `height` is reached.
632 /// The height at which we'll generate and broadcast the spending transaction.
636 use lightning::util::sweep::SpendingDelay as SpendingDelayImport;
637 pub(crate) type nativeSpendingDelay = SpendingDelayImport;
641 pub(crate) fn to_native(&self) -> nativeSpendingDelay {
643 SpendingDelay::Relative {ref num_blocks, } => {
644 let mut num_blocks_nonref = Clone::clone(num_blocks);
645 nativeSpendingDelay::Relative {
646 num_blocks: num_blocks_nonref,
649 SpendingDelay::Absolute {ref height, } => {
650 let mut height_nonref = Clone::clone(height);
651 nativeSpendingDelay::Absolute {
652 height: height_nonref,
658 pub(crate) fn into_native(self) -> nativeSpendingDelay {
660 SpendingDelay::Relative {mut num_blocks, } => {
661 nativeSpendingDelay::Relative {
662 num_blocks: num_blocks,
665 SpendingDelay::Absolute {mut height, } => {
666 nativeSpendingDelay::Absolute {
673 pub(crate) fn from_native(native: &SpendingDelayImport) -> Self {
674 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeSpendingDelay) };
676 nativeSpendingDelay::Relative {ref num_blocks, } => {
677 let mut num_blocks_nonref = Clone::clone(num_blocks);
678 SpendingDelay::Relative {
679 num_blocks: num_blocks_nonref,
682 nativeSpendingDelay::Absolute {ref height, } => {
683 let mut height_nonref = Clone::clone(height);
684 SpendingDelay::Absolute {
685 height: height_nonref,
691 pub(crate) fn native_into(native: nativeSpendingDelay) -> Self {
693 nativeSpendingDelay::Relative {mut num_blocks, } => {
694 SpendingDelay::Relative {
695 num_blocks: num_blocks,
698 nativeSpendingDelay::Absolute {mut height, } => {
699 SpendingDelay::Absolute {
706 /// Frees any resources used by the SpendingDelay
708 pub extern "C" fn SpendingDelay_free(this_ptr: SpendingDelay) { }
709 /// Creates a copy of the SpendingDelay
711 pub extern "C" fn SpendingDelay_clone(orig: &SpendingDelay) -> SpendingDelay {
715 /// Used only if an object of this type is returned as a trait impl by a method
716 pub(crate) extern "C" fn SpendingDelay_clone_void(this_ptr: *const c_void) -> *mut c_void {
717 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const SpendingDelay)).clone() })) as *mut c_void
720 /// Used only if an object of this type is returned as a trait impl by a method
721 pub(crate) extern "C" fn SpendingDelay_free_void(this_ptr: *mut c_void) {
722 let _ = unsafe { Box::from_raw(this_ptr as *mut SpendingDelay) };
725 /// Utility method to constructs a new Relative-variant SpendingDelay
726 pub extern "C" fn SpendingDelay_relative(num_blocks: u32) -> SpendingDelay {
727 SpendingDelay::Relative {
732 /// Utility method to constructs a new Absolute-variant SpendingDelay
733 pub extern "C" fn SpendingDelay_absolute(height: u32) -> SpendingDelay {
734 SpendingDelay::Absolute {
738 /// Get a string which allows debug introspection of a SpendingDelay object
739 pub extern "C" fn SpendingDelay_debug_str_void(o: *const c_void) -> Str {
740 alloc::format!("{:?}", unsafe { o as *const crate::lightning::util::sweep::SpendingDelay }).into()}
742 /// Read a OutputSweeper from a byte array, created by OutputSweeper_write
743 pub extern "C" fn OutputSweeper_read(ser: crate::c_types::u8slice, arg_a: crate::lightning::chain::chaininterface::BroadcasterInterface, arg_b: crate::lightning::chain::chaininterface::FeeEstimator, arg_c: crate::c_types::derived::COption_FilterZ, arg_d: crate::lightning::sign::OutputSpender, arg_e: crate::lightning::sign::ChangeDestinationSource, arg_f: crate::lightning::util::persist::KVStore, arg_g: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_OutputSweeperDecodeErrorZ {
744 let arg_a_conv = arg_a;
745 let arg_b_conv = arg_b;
746 let mut local_arg_c = { /*arg_c*/ let arg_c_opt = arg_c; if arg_c_opt.is_none() { None } else { Some({ { { arg_c_opt.take() } }})} };
747 let arg_c_conv = local_arg_c;
748 let arg_d_conv = arg_d;
749 let arg_e_conv = arg_e;
750 let arg_f_conv = arg_f;
751 let arg_g_conv = arg_g;
752 let arg_conv = (arg_a_conv, arg_b_conv, arg_c_conv, arg_d_conv, arg_e_conv, arg_f_conv, arg_g_conv);
753 let res: Result<lightning::util::sweep::OutputSweeper<crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::sign::ChangeDestinationSource, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::chain::Filter, crate::lightning::util::persist::KVStore, crate::lightning::util::logger::Logger, crate::lightning::sign::OutputSpender>, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
754 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::util::sweep::OutputSweeper { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() };
758 /// Read a C2Tuple_BestBlockOutputSweeperZ from a byte array, created by C2Tuple_BestBlockOutputSweeperZ_write
759 pub extern "C" fn C2Tuple_BestBlockOutputSweeperZ_read(ser: crate::c_types::u8slice, arg_a: crate::lightning::chain::chaininterface::BroadcasterInterface, arg_b: crate::lightning::chain::chaininterface::FeeEstimator, arg_c: crate::c_types::derived::COption_FilterZ, arg_d: crate::lightning::sign::OutputSpender, arg_e: crate::lightning::sign::ChangeDestinationSource, arg_f: crate::lightning::util::persist::KVStore, arg_g: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_C2Tuple_BestBlockOutputSweeperZDecodeErrorZ {
760 let arg_a_conv = arg_a;
761 let arg_b_conv = arg_b;
762 let mut local_arg_c = { /*arg_c*/ let arg_c_opt = arg_c; if arg_c_opt.is_none() { None } else { Some({ { { arg_c_opt.take() } }})} };
763 let arg_c_conv = local_arg_c;
764 let arg_d_conv = arg_d;
765 let arg_e_conv = arg_e;
766 let arg_f_conv = arg_f;
767 let arg_g_conv = arg_g;
768 let arg_conv = (arg_a_conv, arg_b_conv, arg_c_conv, arg_d_conv, arg_e_conv, arg_f_conv, arg_g_conv);
769 let res: Result<(lightning::chain::BestBlock, lightning::util::sweep::OutputSweeper<crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::sign::ChangeDestinationSource, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::chain::Filter, crate::lightning::util::persist::KVStore, crate::lightning::util::logger::Logger, crate::lightning::sign::OutputSpender>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
770 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(orig_res_0_0), is_owned: true }, crate::lightning::util::sweep::OutputSweeper { inner: ObjOps::heap_alloc(orig_res_0_1), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() };