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 //! Structs and traits which allow other parts of rust-lightning to interact with the blockchain.
11 use alloc::str::FromStr;
12 use alloc::string::String;
13 use core::ffi::c_void;
14 use core::convert::Infallible;
15 use bitcoin::hashes::Hash;
16 use crate::c_types::*;
17 #[cfg(feature="no-std")]
18 use alloc::{vec::Vec, boxed::Box};
20 pub mod chaininterface;
22 pub mod channelmonitor;
26 use alloc::str::FromStr;
27 use alloc::string::String;
28 use core::ffi::c_void;
29 use core::convert::Infallible;
30 use bitcoin::hashes::Hash;
31 use crate::c_types::*;
32 #[cfg(feature="no-std")]
33 use alloc::{vec::Vec, boxed::Box};
38 use alloc::str::FromStr;
39 use alloc::string::String;
40 use core::ffi::c_void;
41 use core::convert::Infallible;
42 use bitcoin::hashes::Hash;
43 use crate::c_types::*;
44 #[cfg(feature="no-std")]
45 use alloc::{vec::Vec, boxed::Box};
49 use lightning::chain::BestBlock as nativeBestBlockImport;
50 pub(crate) type nativeBestBlock = nativeBestBlockImport;
52 /// The best known block as identified by its hash and height.
55 pub struct BestBlock {
56 /// A pointer to the opaque Rust object.
58 /// Nearly everywhere, inner must be non-null, however in places where
59 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
60 pub inner: *mut nativeBestBlock,
61 /// Indicates that this is the only struct which contains the same pointer.
63 /// Rust functions which take ownership of an object provided via an argument require
64 /// this to be true and invalidate the object pointed to by inner.
68 impl Drop for BestBlock {
70 if self.is_owned && !<*mut nativeBestBlock>::is_null(self.inner) {
71 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
75 /// Frees any resources used by the BestBlock, if is_owned is set and inner is non-NULL.
77 pub extern "C" fn BestBlock_free(this_obj: BestBlock) { }
79 /// Used only if an object of this type is returned as a trait impl by a method
80 pub(crate) extern "C" fn BestBlock_free_void(this_ptr: *mut c_void) {
81 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeBestBlock) };
85 pub(crate) fn get_native_ref(&self) -> &'static nativeBestBlock {
86 unsafe { &*ObjOps::untweak_ptr(self.inner) }
88 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBestBlock {
89 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
91 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
92 pub(crate) fn take_inner(mut self) -> *mut nativeBestBlock {
93 assert!(self.is_owned);
94 let ret = ObjOps::untweak_ptr(self.inner);
95 self.inner = core::ptr::null_mut();
99 impl Clone for BestBlock {
100 fn clone(&self) -> Self {
102 inner: if <*mut nativeBestBlock>::is_null(self.inner) { core::ptr::null_mut() } else {
103 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
109 /// Used only if an object of this type is returned as a trait impl by a method
110 pub(crate) extern "C" fn BestBlock_clone_void(this_ptr: *const c_void) -> *mut c_void {
111 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeBestBlock)).clone() })) as *mut c_void
114 /// Creates a copy of the BestBlock
115 pub extern "C" fn BestBlock_clone(orig: &BestBlock) -> BestBlock {
118 /// Checks if two BestBlocks contain equal inner contents.
119 /// This ignores pointers and is_owned flags and looks at the values in fields.
120 /// Two objects with NULL inner values will be considered "equal" here.
122 pub extern "C" fn BestBlock_eq(a: &BestBlock, b: &BestBlock) -> bool {
123 if a.inner == b.inner { return true; }
124 if a.inner.is_null() || b.inner.is_null() { return false; }
125 if a.get_native_ref() == b.get_native_ref() { true } else { false }
127 /// Constructs a `BestBlock` that represents the genesis block at height 0 of the given
131 pub extern "C" fn BestBlock_from_network(mut network: crate::bitcoin::network::Network) -> crate::lightning::chain::BestBlock {
132 let mut ret = lightning::chain::BestBlock::from_network(network.into_bitcoin());
133 crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
136 /// Returns a `BestBlock` as identified by the given block hash and height.
139 pub extern "C" fn BestBlock_new(mut block_hash: crate::c_types::ThirtyTwoBytes, mut height: u32) -> crate::lightning::chain::BestBlock {
140 let mut ret = lightning::chain::BestBlock::new(::bitcoin::hash_types::BlockHash::from_slice(&block_hash.data[..]).unwrap(), height);
141 crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
144 /// Returns the best block hash.
147 pub extern "C" fn BestBlock_block_hash(this_arg: &crate::lightning::chain::BestBlock) -> crate::c_types::ThirtyTwoBytes {
148 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_hash();
149 crate::c_types::ThirtyTwoBytes { data: *ret.as_ref() }
152 /// Returns the best block height.
155 pub extern "C" fn BestBlock_height(this_arg: &crate::lightning::chain::BestBlock) -> u32 {
156 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.height();
160 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
163 /// Useful when needing to replay chain data upon startup or as new chain events occur. Clients
164 /// sourcing chain data using a block-oriented API should prefer this interface over [`Confirm`].
165 /// Such clients fetch the entire header chain whereas clients using [`Confirm`] only fetch headers
168 /// By using [`Listen::filtered_block_connected`] this interface supports clients fetching the
169 /// entire header chain and only blocks with matching transaction data using BIP 157 filters or
170 /// other similar filtering.
173 /// An opaque pointer which is passed to your function implementations as an argument.
174 /// This has no meaning in the LDK, and can be NULL or any other value.
175 pub this_arg: *mut c_void,
176 /// Notifies the listener that a block was added at the given height, with the transaction data
177 /// possibly filtered.
178 pub filtered_block_connected: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, height: u32),
179 /// Notifies the listener that a block was added at the given height.
180 pub block_connected: extern "C" fn (this_arg: *const c_void, block: crate::c_types::u8slice, height: u32),
181 /// Notifies the listener that a block was removed at the given height.
182 pub block_disconnected: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
183 /// Frees any resources associated with this object given its this_arg pointer.
184 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
185 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
187 unsafe impl Send for Listen {}
188 unsafe impl Sync for Listen {}
190 pub(crate) fn Listen_clone_fields(orig: &Listen) -> Listen {
192 this_arg: orig.this_arg,
193 filtered_block_connected: Clone::clone(&orig.filtered_block_connected),
194 block_connected: Clone::clone(&orig.block_connected),
195 block_disconnected: Clone::clone(&orig.block_disconnected),
196 free: Clone::clone(&orig.free),
200 use lightning::chain::Listen as rustListen;
201 impl rustListen for Listen {
202 fn filtered_block_connected(&self, mut header: &bitcoin::blockdata::block::Header, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
203 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
204 let mut local_txdata = Vec::new(); for item in txdata.iter() { local_txdata.push( { let (mut orig_txdata_0_0, mut orig_txdata_0_1) = item; let mut local_txdata_0 = (orig_txdata_0_0, crate::c_types::Transaction::from_bitcoin(&orig_txdata_0_1)).into(); local_txdata_0 }); };
205 (self.filtered_block_connected)(self.this_arg, &local_header, local_txdata.into(), height)
207 fn block_connected(&self, mut block: &bitcoin::blockdata::block::Block, mut height: u32) {
208 let mut local_block = ::bitcoin::consensus::encode::serialize(block);
209 (self.block_connected)(self.this_arg, crate::c_types::u8slice::from_slice(&local_block), height)
211 fn block_disconnected(&self, mut header: &bitcoin::blockdata::block::Header, mut height: u32) {
212 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
213 (self.block_disconnected)(self.this_arg, &local_header, height)
217 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
218 // directly as a Deref trait in higher-level structs:
219 impl core::ops::Deref for Listen {
221 fn deref(&self) -> &Self {
225 impl core::ops::DerefMut for Listen {
226 fn deref_mut(&mut self) -> &mut Self {
230 /// Calls the free function if one is set
232 pub extern "C" fn Listen_free(this_ptr: Listen) { }
233 impl Drop for Listen {
235 if let Some(f) = self.free {
240 /// The `Confirm` trait is used to notify LDK when relevant transactions have been confirmed on
241 /// chain or unconfirmed during a chain reorganization.
243 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
244 /// [`Listen`]. For instance, an Electrum-based transaction sync implementation may implement
245 /// [`Filter`] to subscribe to relevant transactions and unspent outputs it should monitor for
246 /// on-chain activity. Then, it needs to notify LDK via this interface upon observing any changes
247 /// with reference to the confirmation status of the monitored objects.
250 /// The intended use is as follows:
251 /// - Call [`transactions_confirmed`] to notify LDK whenever any of the registered transactions or
252 /// outputs are, respectively, confirmed or spent on chain.
253 /// - Call [`transaction_unconfirmed`] to notify LDK whenever any transaction returned by
254 /// [`get_relevant_txids`] is no longer confirmed in the block with the given block hash.
255 /// - Call [`best_block_updated`] to notify LDK whenever a new chain tip becomes available.
259 /// Clients must call these methods in chain order. Specifically:
260 /// - Transactions which are confirmed in a particular block must be given before transactions
261 /// confirmed in a later block.
262 /// - Dependent transactions within the same block must be given in topological order, possibly in
264 /// - All unconfirmed transactions must be given after the original confirmations and before *any*
265 /// reconfirmations, i.e., [`transactions_confirmed`] and [`transaction_unconfirmed`] calls should
266 /// never be interleaved, but always conduced *en bloc*.
267 /// - Any reconfirmed transactions need to be explicitly unconfirmed before they are reconfirmed
268 /// in regard to the new block.
270 /// See individual method documentation for further details.
272 /// [`transactions_confirmed`]: Self::transactions_confirmed
273 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
274 /// [`best_block_updated`]: Self::best_block_updated
275 /// [`get_relevant_txids`]: Self::get_relevant_txids
278 /// An opaque pointer which is passed to your function implementations as an argument.
279 /// This has no meaning in the LDK, and can be NULL or any other value.
280 pub this_arg: *mut c_void,
281 /// Notifies LDK of transactions confirmed in a block with a given header and height.
283 /// Must be called for any transactions registered by [`Filter::register_tx`] or any
284 /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
285 /// appearing in the same block do not need to be included in the same call; instead, multiple
286 /// calls with additional transactions may be made so long as they are made in [chain order].
288 /// May be called before or after [`best_block_updated`] for the corresponding block. However,
289 /// in the event of a chain reorganization, it must not be called with a `header` that is no
290 /// longer in the chain as of the last call to [`best_block_updated`].
292 /// [chain order]: Confirm#order
293 /// [`best_block_updated`]: Self::best_block_updated
294 pub transactions_confirmed: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, height: u32),
295 /// Notifies LDK of a transaction that is no longer confirmed as result of a chain reorganization.
297 /// Must be called for any transaction returned by [`get_relevant_txids`] if it has been
298 /// reorganized out of the best chain or if it is no longer confirmed in the block with the
299 /// given block hash. Once called, the given transaction will not be returned
300 /// by [`get_relevant_txids`], unless it has been reconfirmed via [`transactions_confirmed`].
302 /// [`get_relevant_txids`]: Self::get_relevant_txids
303 /// [`transactions_confirmed`]: Self::transactions_confirmed
304 pub transaction_unconfirmed: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32]),
305 /// Notifies LDK of an update to the best header connected at the given height.
307 /// Must be called whenever a new chain tip becomes available. May be skipped for intermediary
309 pub best_block_updated: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
310 /// Returns transactions that must be monitored for reorganization out of the chain along
311 /// with the height and the hash of the block as part of which it had been previously confirmed.
313 /// Note that the returned `Option<BlockHash>` might be `None` for channels created with LDK
314 /// 0.0.112 and prior, in which case you need to manually track previous confirmations.
316 /// Will include any transactions passed to [`transactions_confirmed`] that have insufficient
317 /// confirmations to be safe from a chain reorganization. Will not include any transactions
318 /// passed to [`transaction_unconfirmed`], unless later reconfirmed.
320 /// Must be called to determine the subset of transactions that must be monitored for
321 /// reorganization. Will be idempotent between calls but may change as a result of calls to the
322 /// other interface methods. Thus, this is useful to determine which transactions must be
323 /// given to [`transaction_unconfirmed`].
325 /// If any of the returned transactions are confirmed in a block other than the one with the
326 /// given hash at the given height, they need to be unconfirmed and reconfirmed via
327 /// [`transaction_unconfirmed`] and [`transactions_confirmed`], respectively.
329 /// [`transactions_confirmed`]: Self::transactions_confirmed
330 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
331 pub get_relevant_txids: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C3Tuple_ThirtyTwoBytesu32COption_ThirtyTwoBytesZZZ,
332 /// Frees any resources associated with this object given its this_arg pointer.
333 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
334 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
336 unsafe impl Send for Confirm {}
337 unsafe impl Sync for Confirm {}
339 pub(crate) fn Confirm_clone_fields(orig: &Confirm) -> Confirm {
341 this_arg: orig.this_arg,
342 transactions_confirmed: Clone::clone(&orig.transactions_confirmed),
343 transaction_unconfirmed: Clone::clone(&orig.transaction_unconfirmed),
344 best_block_updated: Clone::clone(&orig.best_block_updated),
345 get_relevant_txids: Clone::clone(&orig.get_relevant_txids),
346 free: Clone::clone(&orig.free),
350 use lightning::chain::Confirm as rustConfirm;
351 impl rustConfirm for Confirm {
352 fn transactions_confirmed(&self, mut header: &bitcoin::blockdata::block::Header, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
353 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
354 let mut local_txdata = Vec::new(); for item in txdata.iter() { local_txdata.push( { let (mut orig_txdata_0_0, mut orig_txdata_0_1) = item; let mut local_txdata_0 = (orig_txdata_0_0, crate::c_types::Transaction::from_bitcoin(&orig_txdata_0_1)).into(); local_txdata_0 }); };
355 (self.transactions_confirmed)(self.this_arg, &local_header, local_txdata.into(), height)
357 fn transaction_unconfirmed(&self, mut txid: &bitcoin::hash_types::Txid) {
358 (self.transaction_unconfirmed)(self.this_arg, txid.as_ref())
360 fn best_block_updated(&self, mut header: &bitcoin::blockdata::block::Header, mut height: u32) {
361 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
362 (self.best_block_updated)(self.this_arg, &local_header, height)
364 fn get_relevant_txids(&self) -> Vec<(bitcoin::hash_types::Txid, u32, Option<bitcoin::hash_types::BlockHash>)> {
365 let mut ret = (self.get_relevant_txids)(self.this_arg);
366 let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = item.to_rust(); let mut local_orig_ret_0_2 = { /*orig_ret_0_2*/ let orig_ret_0_2_opt = orig_ret_0_2; if orig_ret_0_2_opt.is_none() { None } else { Some({ { ::bitcoin::hash_types::BlockHash::from_slice(&{ orig_ret_0_2_opt.take() }.data[..]).unwrap() }})} }; let mut local_ret_0 = (::bitcoin::hash_types::Txid::from_slice(&orig_ret_0_0.data[..]).unwrap(), orig_ret_0_1, local_orig_ret_0_2); local_ret_0 }); };
371 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
372 // directly as a Deref trait in higher-level structs:
373 impl core::ops::Deref for Confirm {
375 fn deref(&self) -> &Self {
379 impl core::ops::DerefMut for Confirm {
380 fn deref_mut(&mut self) -> &mut Self {
384 /// Calls the free function if one is set
386 pub extern "C" fn Confirm_free(this_ptr: Confirm) { }
387 impl Drop for Confirm {
389 if let Some(f) = self.free {
394 /// An enum representing the status of a channel monitor update persistence.
396 /// These are generally used as the return value for an implementation of [`Persist`] which is used
397 /// as the storage layer for a [`ChainMonitor`]. See the docs on [`Persist`] for a high-level
398 /// explanation of how to handle different cases.
400 /// While `UnrecoverableError` is provided as a failure variant, it is not truly \"handled\" on the
401 /// calling side, and generally results in an immediate panic. For those who prefer to avoid
402 /// panics, `InProgress` can be used and you can retry the update operation in the background or
403 /// shut down cleanly.
405 /// Note that channels should generally *not* be force-closed after a persistence failure.
406 /// Force-closing with the latest [`ChannelMonitorUpdate`] applied may result in a transaction
407 /// being broadcast which can only be spent by the latest [`ChannelMonitor`]! Thus, if the
408 /// latest [`ChannelMonitor`] is not durably persisted anywhere and exists only in memory, naively
409 /// calling [`ChannelManager::force_close_broadcasting_latest_txn`] *may result in loss of funds*!
411 /// [`Persist`]: chainmonitor::Persist
412 /// [`ChainMonitor`]: chainmonitor::ChainMonitor
413 /// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn
417 pub enum ChannelMonitorUpdateStatus {
418 /// The update has been durably persisted and all copies of the relevant [`ChannelMonitor`]
419 /// have been updated.
421 /// This includes performing any `fsync()` calls required to ensure the update is guaranteed to
422 /// be available on restart even if the application crashes.
424 /// Indicates that the update will happen asynchronously in the background or that a transient
425 /// failure occurred which is being retried in the background and will eventually complete.
427 /// This will \"freeze\" a channel, preventing us from revoking old states or submitting a new
428 /// commitment transaction to the counterparty. Once the update(s) which are `InProgress` have
429 /// been completed, a [`MonitorEvent::Completed`] can be used to restore the channel to an
430 /// operational state.
432 /// Even when a channel has been \"frozen\", updates to the [`ChannelMonitor`] can continue to
433 /// occur (e.g. if an inbound HTLC which we forwarded was claimed upstream, resulting in us
434 /// attempting to claim it on this channel) and those updates must still be persisted.
436 /// No updates to the channel will be made which could invalidate other [`ChannelMonitor`]s
437 /// until a [`MonitorEvent::Completed`] is provided, even if you return no error on a later
438 /// monitor update for the same channel.
440 /// For deployments where a copy of [`ChannelMonitor`]s and other local state are backed up in
441 /// a remote location (with local copies persisted immediately), it is anticipated that all
442 /// updates will return [`InProgress`] until the remote copies could be updated.
444 /// Note that while fully asynchronous persistence of [`ChannelMonitor`] data is generally
445 /// reliable, this feature is considered beta, and a handful of edge-cases remain. Until the
446 /// remaining cases are fixed, in rare cases, *using this feature may lead to funds loss*.
448 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
450 /// Indicates that an update has failed and will not complete at any point in the future.
452 /// Currently returning this variant will cause LDK to immediately panic to encourage immediate
453 /// shutdown. In the future this may be updated to disconnect peers and refuse to continue
454 /// normal operation without a panic.
456 /// Applications which wish to perform an orderly shutdown after failure should consider
457 /// returning [`InProgress`] instead and simply shut down without ever marking the update
460 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
463 use lightning::chain::ChannelMonitorUpdateStatus as ChannelMonitorUpdateStatusImport;
464 pub(crate) type nativeChannelMonitorUpdateStatus = ChannelMonitorUpdateStatusImport;
466 impl ChannelMonitorUpdateStatus {
468 pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateStatus {
470 ChannelMonitorUpdateStatus::Completed => nativeChannelMonitorUpdateStatus::Completed,
471 ChannelMonitorUpdateStatus::InProgress => nativeChannelMonitorUpdateStatus::InProgress,
472 ChannelMonitorUpdateStatus::UnrecoverableError => nativeChannelMonitorUpdateStatus::UnrecoverableError,
476 pub(crate) fn into_native(self) -> nativeChannelMonitorUpdateStatus {
478 ChannelMonitorUpdateStatus::Completed => nativeChannelMonitorUpdateStatus::Completed,
479 ChannelMonitorUpdateStatus::InProgress => nativeChannelMonitorUpdateStatus::InProgress,
480 ChannelMonitorUpdateStatus::UnrecoverableError => nativeChannelMonitorUpdateStatus::UnrecoverableError,
484 pub(crate) fn from_native(native: &ChannelMonitorUpdateStatusImport) -> Self {
485 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeChannelMonitorUpdateStatus) };
487 nativeChannelMonitorUpdateStatus::Completed => ChannelMonitorUpdateStatus::Completed,
488 nativeChannelMonitorUpdateStatus::InProgress => ChannelMonitorUpdateStatus::InProgress,
489 nativeChannelMonitorUpdateStatus::UnrecoverableError => ChannelMonitorUpdateStatus::UnrecoverableError,
493 pub(crate) fn native_into(native: nativeChannelMonitorUpdateStatus) -> Self {
495 nativeChannelMonitorUpdateStatus::Completed => ChannelMonitorUpdateStatus::Completed,
496 nativeChannelMonitorUpdateStatus::InProgress => ChannelMonitorUpdateStatus::InProgress,
497 nativeChannelMonitorUpdateStatus::UnrecoverableError => ChannelMonitorUpdateStatus::UnrecoverableError,
501 /// Creates a copy of the ChannelMonitorUpdateStatus
503 pub extern "C" fn ChannelMonitorUpdateStatus_clone(orig: &ChannelMonitorUpdateStatus) -> ChannelMonitorUpdateStatus {
507 /// Used only if an object of this type is returned as a trait impl by a method
508 pub(crate) extern "C" fn ChannelMonitorUpdateStatus_clone_void(this_ptr: *const c_void) -> *mut c_void {
509 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const ChannelMonitorUpdateStatus)).clone() })) as *mut c_void
512 /// Used only if an object of this type is returned as a trait impl by a method
513 pub(crate) extern "C" fn ChannelMonitorUpdateStatus_free_void(this_ptr: *mut c_void) {
514 let _ = unsafe { Box::from_raw(this_ptr as *mut ChannelMonitorUpdateStatus) };
517 /// Utility method to constructs a new Completed-variant ChannelMonitorUpdateStatus
518 pub extern "C" fn ChannelMonitorUpdateStatus_completed() -> ChannelMonitorUpdateStatus {
519 ChannelMonitorUpdateStatus::Completed}
521 /// Utility method to constructs a new InProgress-variant ChannelMonitorUpdateStatus
522 pub extern "C" fn ChannelMonitorUpdateStatus_in_progress() -> ChannelMonitorUpdateStatus {
523 ChannelMonitorUpdateStatus::InProgress}
525 /// Utility method to constructs a new UnrecoverableError-variant ChannelMonitorUpdateStatus
526 pub extern "C" fn ChannelMonitorUpdateStatus_unrecoverable_error() -> ChannelMonitorUpdateStatus {
527 ChannelMonitorUpdateStatus::UnrecoverableError}
528 /// Get a string which allows debug introspection of a ChannelMonitorUpdateStatus object
529 pub extern "C" fn ChannelMonitorUpdateStatus_debug_str_void(o: *const c_void) -> Str {
530 alloc::format!("{:?}", unsafe { o as *const crate::lightning::chain::ChannelMonitorUpdateStatus }).into()}
531 /// Checks if two ChannelMonitorUpdateStatuss contain equal inner contents.
532 /// This ignores pointers and is_owned flags and looks at the values in fields.
534 pub extern "C" fn ChannelMonitorUpdateStatus_eq(a: &ChannelMonitorUpdateStatus, b: &ChannelMonitorUpdateStatus) -> bool {
535 if &a.to_native() == &b.to_native() { true } else { false }
537 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
538 /// blocks are connected and disconnected.
540 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
541 /// responsible for maintaining a set of monitors such that they can be updated as channel state
542 /// changes. On each update, *all copies* of a [`ChannelMonitor`] must be updated and the update
543 /// persisted to disk to ensure that the latest [`ChannelMonitor`] state can be reloaded if the
544 /// application crashes.
546 /// See method documentation and [`ChannelMonitorUpdateStatus`] for specific requirements.
549 /// An opaque pointer which is passed to your function implementations as an argument.
550 /// This has no meaning in the LDK, and can be NULL or any other value.
551 pub this_arg: *mut c_void,
552 /// Watches a channel identified by `funding_txo` using `monitor`.
554 /// Implementations are responsible for watching the chain for the funding transaction along
555 /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
556 /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
558 /// A return of `Err(())` indicates that the channel should immediately be force-closed without
559 /// broadcasting the funding transaction.
561 /// If the given `funding_txo` has previously been registered via `watch_channel`, `Err(())`
562 /// must be returned.
564 /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
565 /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
566 /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
567 pub watch_channel: extern "C" fn (this_arg: *const c_void, funding_txo: crate::lightning::chain::transaction::OutPoint, monitor: crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_ChannelMonitorUpdateStatusNoneZ,
568 /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
570 /// Implementations must call [`ChannelMonitor::update_monitor`] with the given update. This
571 /// may fail (returning an `Err(())`), in which case this should return
572 /// [`ChannelMonitorUpdateStatus::InProgress`] (and the update should never complete). This
573 /// generally implies the channel has been closed (either by the funding outpoint being spent
574 /// on-chain or the [`ChannelMonitor`] having decided to do so and broadcasted a transaction),
575 /// and the [`ChannelManager`] state will be updated once it sees the funding spend on-chain.
577 /// In general, persistence failures should be retried after returning
578 /// [`ChannelMonitorUpdateStatus::InProgress`] and eventually complete. If a failure truly
579 /// cannot be retried, the node should shut down immediately after returning
580 /// [`ChannelMonitorUpdateStatus::UnrecoverableError`], see its documentation for more info.
582 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
583 pub update_channel: extern "C" fn (this_arg: *const c_void, funding_txo: crate::lightning::chain::transaction::OutPoint, update: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate) -> crate::lightning::chain::ChannelMonitorUpdateStatus,
584 /// Returns any monitor events since the last call. Subsequent calls must only return new
587 /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
588 /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
591 /// For details on asynchronous [`ChannelMonitor`] updating and returning
592 /// [`MonitorEvent::Completed`] here, see [`ChannelMonitorUpdateStatus::InProgress`].
593 pub release_pending_monitor_events: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C3Tuple_OutPointCVec_MonitorEventZPublicKeyZZ,
594 /// Frees any resources associated with this object given its this_arg pointer.
595 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
596 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
598 unsafe impl Send for Watch {}
599 unsafe impl Sync for Watch {}
601 pub(crate) fn Watch_clone_fields(orig: &Watch) -> Watch {
603 this_arg: orig.this_arg,
604 watch_channel: Clone::clone(&orig.watch_channel),
605 update_channel: Clone::clone(&orig.update_channel),
606 release_pending_monitor_events: Clone::clone(&orig.release_pending_monitor_events),
607 free: Clone::clone(&orig.free),
611 use lightning::chain::Watch as rustWatch;
612 impl rustWatch<crate::lightning::sign::ecdsa::WriteableEcdsaChannelSigner> for Watch {
613 fn watch_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut monitor: lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::sign::ecdsa::WriteableEcdsaChannelSigner>) -> Result<lightning::chain::ChannelMonitorUpdateStatus, ()> {
614 let mut ret = (self.watch_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(funding_txo), is_owned: true }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: ObjOps::heap_alloc(monitor), is_owned: true });
615 let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_native() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })};
618 fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: &lightning::chain::channelmonitor::ChannelMonitorUpdate) -> lightning::chain::ChannelMonitorUpdateStatus {
619 let mut ret = (self.update_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(funding_txo), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { ObjOps::nonnull_ptr_to_inner((update as *const lightning::chain::channelmonitor::ChannelMonitorUpdate<>) as *mut _) }, is_owned: false });
622 fn release_pending_monitor_events(&self) -> Vec<(lightning::chain::transaction::OutPoint, Vec<lightning::chain::channelmonitor::MonitorEvent>, Option<bitcoin::secp256k1::PublicKey>)> {
623 let mut ret = (self.release_pending_monitor_events)(self.this_arg);
624 let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = item.to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_native() }); }; let mut local_orig_ret_0_2 = if orig_ret_0_2.is_null() { None } else { Some( { orig_ret_0_2.into_rust() }) }; let mut local_ret_0 = (*unsafe { Box::from_raw(orig_ret_0_0.take_inner()) }, local_orig_ret_0_1, local_orig_ret_0_2); local_ret_0 }); };
629 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
630 // directly as a Deref trait in higher-level structs:
631 impl core::ops::Deref for Watch {
633 fn deref(&self) -> &Self {
637 impl core::ops::DerefMut for Watch {
638 fn deref_mut(&mut self) -> &mut Self {
642 /// Calls the free function if one is set
644 pub extern "C" fn Watch_free(this_ptr: Watch) { }
645 impl Drop for Watch {
647 if let Some(f) = self.free {
652 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
655 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
656 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
657 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
658 /// receiving full blocks from a chain source, any further filtering is unnecessary.
660 /// After an output has been registered, subsequent block retrievals from the chain source must not
661 /// exclude any transactions matching the new criteria nor any in-block descendants of such
664 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
665 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
666 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
667 /// invocation that has called the `Filter` must return [`InProgress`].
669 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
670 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
671 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
674 /// An opaque pointer which is passed to your function implementations as an argument.
675 /// This has no meaning in the LDK, and can be NULL or any other value.
676 pub this_arg: *mut c_void,
677 /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
678 /// a spending condition.
679 pub register_tx: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32], script_pubkey: crate::c_types::u8slice),
680 /// Registers interest in spends of a transaction output.
682 /// Note that this method might be called during processing of a new block. You therefore need
683 /// to ensure that also dependent output spents within an already connected block are correctly
684 /// handled, e.g., by re-scanning the block in question whenever new outputs have been
685 /// registered mid-processing.
686 pub register_output: extern "C" fn (this_arg: *const c_void, output: crate::lightning::chain::WatchedOutput),
687 /// Frees any resources associated with this object given its this_arg pointer.
688 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
689 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
691 unsafe impl Send for Filter {}
692 unsafe impl Sync for Filter {}
694 pub(crate) fn Filter_clone_fields(orig: &Filter) -> Filter {
696 this_arg: orig.this_arg,
697 register_tx: Clone::clone(&orig.register_tx),
698 register_output: Clone::clone(&orig.register_output),
699 free: Clone::clone(&orig.free),
703 use lightning::chain::Filter as rustFilter;
704 impl rustFilter for Filter {
705 fn register_tx(&self, mut txid: &bitcoin::hash_types::Txid, mut script_pubkey: &bitcoin::blockdata::script::Script) {
706 (self.register_tx)(self.this_arg, txid.as_ref(), crate::c_types::u8slice::from_slice(script_pubkey.as_ref()))
708 fn register_output(&self, mut output: lightning::chain::WatchedOutput) {
709 (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: ObjOps::heap_alloc(output), is_owned: true })
713 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
714 // directly as a Deref trait in higher-level structs:
715 impl core::ops::Deref for Filter {
717 fn deref(&self) -> &Self {
721 impl core::ops::DerefMut for Filter {
722 fn deref_mut(&mut self) -> &mut Self {
726 /// Calls the free function if one is set
728 pub extern "C" fn Filter_free(this_ptr: Filter) { }
729 impl Drop for Filter {
731 if let Some(f) = self.free {
737 use lightning::chain::WatchedOutput as nativeWatchedOutputImport;
738 pub(crate) type nativeWatchedOutput = nativeWatchedOutputImport;
740 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
742 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
743 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
744 /// [`Confirm::transactions_confirmed`].
746 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
747 /// may have been spent there. See [`Filter::register_output`] for details.
749 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
750 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
753 pub struct WatchedOutput {
754 /// A pointer to the opaque Rust object.
756 /// Nearly everywhere, inner must be non-null, however in places where
757 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
758 pub inner: *mut nativeWatchedOutput,
759 /// Indicates that this is the only struct which contains the same pointer.
761 /// Rust functions which take ownership of an object provided via an argument require
762 /// this to be true and invalidate the object pointed to by inner.
766 impl Drop for WatchedOutput {
768 if self.is_owned && !<*mut nativeWatchedOutput>::is_null(self.inner) {
769 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
773 /// Frees any resources used by the WatchedOutput, if is_owned is set and inner is non-NULL.
775 pub extern "C" fn WatchedOutput_free(this_obj: WatchedOutput) { }
777 /// Used only if an object of this type is returned as a trait impl by a method
778 pub(crate) extern "C" fn WatchedOutput_free_void(this_ptr: *mut c_void) {
779 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeWatchedOutput) };
783 pub(crate) fn get_native_ref(&self) -> &'static nativeWatchedOutput {
784 unsafe { &*ObjOps::untweak_ptr(self.inner) }
786 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeWatchedOutput {
787 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
789 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
790 pub(crate) fn take_inner(mut self) -> *mut nativeWatchedOutput {
791 assert!(self.is_owned);
792 let ret = ObjOps::untweak_ptr(self.inner);
793 self.inner = core::ptr::null_mut();
797 /// First block where the transaction output may have been spent.
799 pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crate::c_types::derived::COption_ThirtyTwoBytesZ {
800 let mut inner_val = &mut this_ptr.get_native_mut_ref().block_hash;
801 let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_ThirtyTwoBytesZ::None } else { crate::c_types::derived::COption_ThirtyTwoBytesZ::Some(/* WARNING: CLONING CONVERSION HERE! &Option<Enum> is otherwise un-expressable. */ { crate::c_types::ThirtyTwoBytes { data: *(*inner_val.as_ref().unwrap()).clone().as_ref() } }) };
804 /// First block where the transaction output may have been spent.
806 pub extern "C" fn WatchedOutput_set_block_hash(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::COption_ThirtyTwoBytesZ) {
807 let mut local_val = { /*val*/ let val_opt = val; if val_opt.is_none() { None } else { Some({ { ::bitcoin::hash_types::BlockHash::from_slice(&{ val_opt.take() }.data[..]).unwrap() }})} };
808 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.block_hash = local_val;
810 /// Outpoint identifying the transaction output.
812 pub extern "C" fn WatchedOutput_get_outpoint(this_ptr: &WatchedOutput) -> crate::lightning::chain::transaction::OutPoint {
813 let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint;
814 crate::lightning::chain::transaction::OutPoint { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning::chain::transaction::OutPoint<>) as *mut _) }, is_owned: false }
816 /// Outpoint identifying the transaction output.
818 pub extern "C" fn WatchedOutput_set_outpoint(this_ptr: &mut WatchedOutput, mut val: crate::lightning::chain::transaction::OutPoint) {
819 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
821 /// Spending condition of the transaction output.
823 pub extern "C" fn WatchedOutput_get_script_pubkey(this_ptr: &WatchedOutput) -> crate::c_types::derived::CVec_u8Z {
824 let mut inner_val = &mut this_ptr.get_native_mut_ref().script_pubkey;
825 inner_val.as_bytes().to_vec().into()
827 /// Spending condition of the transaction output.
829 pub extern "C" fn WatchedOutput_set_script_pubkey(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::CVec_u8Z) {
830 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.script_pubkey = ::bitcoin::blockdata::script::ScriptBuf::from(val.into_rust());
832 /// Constructs a new WatchedOutput given each field
835 pub extern "C" fn WatchedOutput_new(mut block_hash_arg: crate::c_types::derived::COption_ThirtyTwoBytesZ, mut outpoint_arg: crate::lightning::chain::transaction::OutPoint, mut script_pubkey_arg: crate::c_types::derived::CVec_u8Z) -> WatchedOutput {
836 let mut local_block_hash_arg = { /*block_hash_arg*/ let block_hash_arg_opt = block_hash_arg; if block_hash_arg_opt.is_none() { None } else { Some({ { ::bitcoin::hash_types::BlockHash::from_slice(&{ block_hash_arg_opt.take() }.data[..]).unwrap() }})} };
837 WatchedOutput { inner: ObjOps::heap_alloc(nativeWatchedOutput {
838 block_hash: local_block_hash_arg,
839 outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
840 script_pubkey: ::bitcoin::blockdata::script::ScriptBuf::from(script_pubkey_arg.into_rust()),
843 impl Clone for WatchedOutput {
844 fn clone(&self) -> Self {
846 inner: if <*mut nativeWatchedOutput>::is_null(self.inner) { core::ptr::null_mut() } else {
847 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
853 /// Used only if an object of this type is returned as a trait impl by a method
854 pub(crate) extern "C" fn WatchedOutput_clone_void(this_ptr: *const c_void) -> *mut c_void {
855 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeWatchedOutput)).clone() })) as *mut c_void
858 /// Creates a copy of the WatchedOutput
859 pub extern "C" fn WatchedOutput_clone(orig: &WatchedOutput) -> WatchedOutput {
862 /// Checks if two WatchedOutputs contain equal inner contents.
863 /// This ignores pointers and is_owned flags and looks at the values in fields.
864 /// Two objects with NULL inner values will be considered "equal" here.
866 pub extern "C" fn WatchedOutput_eq(a: &WatchedOutput, b: &WatchedOutput) -> bool {
867 if a.inner == b.inner { return true; }
868 if a.inner.is_null() || b.inner.is_null() { return false; }
869 if a.get_native_ref() == b.get_native_ref() { true } else { false }
871 /// Generates a non-cryptographic 64-bit hash of the WatchedOutput.
873 pub extern "C" fn WatchedOutput_hash(o: &WatchedOutput) -> u64 {
874 if o.inner.is_null() { return 0; }
875 // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
877 let mut hasher = core::hash::SipHasher::new();
878 core::hash::Hash::hash(o.get_native_ref(), &mut hasher);
879 core::hash::Hasher::finish(&hasher)