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 *mut 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.into_inner() }
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 {}
189 pub(crate) fn Listen_clone_fields(orig: &Listen) -> Listen {
191 this_arg: orig.this_arg,
192 filtered_block_connected: Clone::clone(&orig.filtered_block_connected),
193 block_connected: Clone::clone(&orig.block_connected),
194 block_disconnected: Clone::clone(&orig.block_disconnected),
195 free: Clone::clone(&orig.free),
199 use lightning::chain::Listen as rustListen;
200 impl rustListen for Listen {
201 fn filtered_block_connected(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
202 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
203 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 }); };
204 (self.filtered_block_connected)(self.this_arg, &local_header, local_txdata.into(), height)
206 fn block_connected(&self, mut block: &bitcoin::blockdata::block::Block, mut height: u32) {
207 let mut local_block = ::bitcoin::consensus::encode::serialize(block);
208 (self.block_connected)(self.this_arg, crate::c_types::u8slice::from_slice(&local_block), height)
210 fn block_disconnected(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
211 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
212 (self.block_disconnected)(self.this_arg, &local_header, height)
216 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
217 // directly as a Deref trait in higher-level structs:
218 impl core::ops::Deref for Listen {
220 fn deref(&self) -> &Self {
224 impl core::ops::DerefMut for Listen {
225 fn deref_mut(&mut self) -> &mut Self {
229 /// Calls the free function if one is set
231 pub extern "C" fn Listen_free(this_ptr: Listen) { }
232 impl Drop for Listen {
234 if let Some(f) = self.free {
239 /// The `Confirm` trait is used to notify LDK when relevant transactions have been confirmed on
240 /// chain or unconfirmed during a chain reorganization.
242 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
243 /// [`Listen`]. For instance, an Electrum-based transaction sync implementation may implement
244 /// [`Filter`] to subscribe to relevant transactions and unspent outputs it should monitor for
245 /// on-chain activity. Then, it needs to notify LDK via this interface upon observing any changes
246 /// with reference to the confirmation status of the monitored objects.
249 /// The intended use is as follows:
250 /// - Call [`transactions_confirmed`] to notify LDK whenever any of the registered transactions or
251 /// outputs are, respectively, confirmed or spent on chain.
252 /// - Call [`transaction_unconfirmed`] to notify LDK whenever any transaction returned by
253 /// [`get_relevant_txids`] is no longer confirmed in the block with the given block hash.
254 /// - Call [`best_block_updated`] to notify LDK whenever a new chain tip becomes available.
258 /// Clients must call these methods in chain order. Specifically:
259 /// - Transactions which are confirmed in a particular block must be given before transactions
260 /// confirmed in a later block.
261 /// - Dependent transactions within the same block must be given in topological order, possibly in
263 /// - All unconfirmed transactions must be given after the original confirmations and before *any*
264 /// reconfirmations, i.e., [`transactions_confirmed`] and [`transaction_unconfirmed`] calls should
265 /// never be interleaved, but always conduced *en bloc*.
266 /// - Any reconfirmed transactions need to be explicitly unconfirmed before they are reconfirmed
267 /// in regard to the new block.
269 /// See individual method documentation for further details.
271 /// [`transactions_confirmed`]: Self::transactions_confirmed
272 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
273 /// [`best_block_updated`]: Self::best_block_updated
274 /// [`get_relevant_txids`]: Self::get_relevant_txids
277 /// An opaque pointer which is passed to your function implementations as an argument.
278 /// This has no meaning in the LDK, and can be NULL or any other value.
279 pub this_arg: *mut c_void,
280 /// Notifies LDK of transactions confirmed in a block with a given header and height.
282 /// Must be called for any transactions registered by [`Filter::register_tx`] or any
283 /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
284 /// appearing in the same block do not need to be included in the same call; instead, multiple
285 /// calls with additional transactions may be made so long as they are made in [chain order].
287 /// May be called before or after [`best_block_updated`] for the corresponding block. However,
288 /// in the event of a chain reorganization, it must not be called with a `header` that is no
289 /// longer in the chain as of the last call to [`best_block_updated`].
291 /// [chain order]: Confirm#order
292 /// [`best_block_updated`]: Self::best_block_updated
293 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),
294 /// Notifies LDK of a transaction that is no longer confirmed as result of a chain reorganization.
296 /// Must be called for any transaction returned by [`get_relevant_txids`] if it has been
297 /// reorganized out of the best chain or if it is no longer confirmed in the block with the
298 /// given block hash. Once called, the given transaction will not be returned
299 /// by [`get_relevant_txids`], unless it has been reconfirmed via [`transactions_confirmed`].
301 /// [`get_relevant_txids`]: Self::get_relevant_txids
302 /// [`transactions_confirmed`]: Self::transactions_confirmed
303 pub transaction_unconfirmed: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32]),
304 /// Notifies LDK of an update to the best header connected at the given height.
306 /// Must be called whenever a new chain tip becomes available. May be skipped for intermediary
308 pub best_block_updated: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
309 /// Returns transactions that must be monitored for reorganization out of the chain along
310 /// with the hash of the block as part of which it had been previously confirmed.
312 /// Note that the returned `Option<BlockHash>` might be `None` for channels created with LDK
313 /// 0.0.112 and prior, in which case you need to manually track previous confirmations.
315 /// Will include any transactions passed to [`transactions_confirmed`] that have insufficient
316 /// confirmations to be safe from a chain reorganization. Will not include any transactions
317 /// passed to [`transaction_unconfirmed`], unless later reconfirmed.
319 /// Must be called to determine the subset of transactions that must be monitored for
320 /// reorganization. Will be idempotent between calls but may change as a result of calls to the
321 /// other interface methods. Thus, this is useful to determine which transactions must be
322 /// given to [`transaction_unconfirmed`].
324 /// If any of the returned transactions are confirmed in a block other than the one with the
325 /// given hash, they need to be unconfirmed and reconfirmed via [`transaction_unconfirmed`] and
326 /// [`transactions_confirmed`], respectively.
328 /// [`transactions_confirmed`]: Self::transactions_confirmed
329 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
330 pub get_relevant_txids: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C2Tuple_ThirtyTwoBytesCOption_ThirtyTwoBytesZZZ,
331 /// Frees any resources associated with this object given its this_arg pointer.
332 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
333 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
335 unsafe impl Send for Confirm {}
336 unsafe impl Sync for Confirm {}
337 pub(crate) fn Confirm_clone_fields(orig: &Confirm) -> Confirm {
339 this_arg: orig.this_arg,
340 transactions_confirmed: Clone::clone(&orig.transactions_confirmed),
341 transaction_unconfirmed: Clone::clone(&orig.transaction_unconfirmed),
342 best_block_updated: Clone::clone(&orig.best_block_updated),
343 get_relevant_txids: Clone::clone(&orig.get_relevant_txids),
344 free: Clone::clone(&orig.free),
348 use lightning::chain::Confirm as rustConfirm;
349 impl rustConfirm for Confirm {
350 fn transactions_confirmed(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
351 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
352 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 }); };
353 (self.transactions_confirmed)(self.this_arg, &local_header, local_txdata.into(), height)
355 fn transaction_unconfirmed(&self, mut txid: &bitcoin::hash_types::Txid) {
356 (self.transaction_unconfirmed)(self.this_arg, txid.as_inner())
358 fn best_block_updated(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
359 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
360 (self.best_block_updated)(self.this_arg, &local_header, height)
362 fn get_relevant_txids(&self) -> Vec<(bitcoin::hash_types::Txid, Option<bitcoin::hash_types::BlockHash>)> {
363 let mut ret = (self.get_relevant_txids)(self.this_arg);
364 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) = item.to_rust(); let mut local_orig_ret_0_1 = { /*orig_ret_0_1*/ let orig_ret_0_1_opt = orig_ret_0_1; if orig_ret_0_1_opt.is_none() { None } else { Some({ { ::bitcoin::hash_types::BlockHash::from_slice(&{ orig_ret_0_1_opt.take() }.data[..]).unwrap() }})} }; let mut local_ret_0 = (::bitcoin::hash_types::Txid::from_slice(&orig_ret_0_0.data[..]).unwrap(), local_orig_ret_0_1); local_ret_0 }); };
369 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
370 // directly as a Deref trait in higher-level structs:
371 impl core::ops::Deref for Confirm {
373 fn deref(&self) -> &Self {
377 impl core::ops::DerefMut for Confirm {
378 fn deref_mut(&mut self) -> &mut Self {
382 /// Calls the free function if one is set
384 pub extern "C" fn Confirm_free(this_ptr: Confirm) { }
385 impl Drop for Confirm {
387 if let Some(f) = self.free {
392 /// An enum representing the status of a channel monitor update persistence.
394 /// These are generally used as the return value for an implementation of [`Persist`] which is used
395 /// as the storage layer for a [`ChainMonitor`]. See the docs on [`Persist`] for a high-level
396 /// explanation of how to handle different cases.
398 /// While `UnrecoverableError` is provided as a failure variant, it is not truly \"handled\" on the
399 /// calling side, and generally results in an immediate panic. For those who prefer to avoid
400 /// panics, `InProgress` can be used and you can retry the update operation in the background or
401 /// shut down cleanly.
403 /// Note that channels should generally *not* be force-closed after a persistence failure.
404 /// Force-closing with the latest [`ChannelMonitorUpdate`] applied may result in a transaction
405 /// being broadcast which can only be spent by the latest [`ChannelMonitor`]! Thus, if the
406 /// latest [`ChannelMonitor`] is not durably persisted anywhere and exists only in memory, naively
407 /// calling [`ChannelManager::force_close_broadcasting_latest_txn`] *may result in loss of funds*!
409 /// [`Persist`]: chainmonitor::Persist
410 /// [`ChainMonitor`]: chainmonitor::ChainMonitor
411 /// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn
415 pub enum ChannelMonitorUpdateStatus {
416 /// The update has been durably persisted and all copies of the relevant [`ChannelMonitor`]
417 /// have been updated.
419 /// This includes performing any `fsync()` calls required to ensure the update is guaranteed to
420 /// be available on restart even if the application crashes.
422 /// Indicates that the update will happen asynchronously in the background or that a transient
423 /// failure occurred which is being retried in the background and will eventually complete.
425 /// This will \"freeze\" a channel, preventing us from revoking old states or submitting a new
426 /// commitment transaction to the counterparty. Once the update(s) which are `InProgress` have
427 /// been completed, a [`MonitorEvent::Completed`] can be used to restore the channel to an
428 /// operational state.
430 /// Even when a channel has been \"frozen\", updates to the [`ChannelMonitor`] can continue to
431 /// occur (e.g. if an inbound HTLC which we forwarded was claimed upstream, resulting in us
432 /// attempting to claim it on this channel) and those updates must still be persisted.
434 /// No updates to the channel will be made which could invalidate other [`ChannelMonitor`]s
435 /// until a [`MonitorEvent::Completed`] is provided, even if you return no error on a later
436 /// monitor update for the same channel.
438 /// For deployments where a copy of [`ChannelMonitor`]s and other local state are backed up in
439 /// a remote location (with local copies persisted immediately), it is anticipated that all
440 /// updates will return [`InProgress`] until the remote copies could be updated.
442 /// Note that while fully asynchronous persistence of [`ChannelMonitor`] data is generally
443 /// reliable, this feature is considered beta, and a handful of edge-cases remain. Until the
444 /// remaining cases are fixed, in rare cases, *using this feature may lead to funds loss*.
446 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
448 /// Indicates that an update has failed and will not complete at any point in the future.
450 /// Currently returning this variant will cause LDK to immediately panic to encourage immediate
451 /// shutdown. In the future this may be updated to disconnect peers and refuse to continue
452 /// normal operation without a panic.
454 /// Applications which wish to perform an orderly shutdown after failure should consider
455 /// returning [`InProgress`] instead and simply shut down without ever marking the update
458 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
461 use lightning::chain::ChannelMonitorUpdateStatus as ChannelMonitorUpdateStatusImport;
462 pub(crate) type nativeChannelMonitorUpdateStatus = ChannelMonitorUpdateStatusImport;
464 impl ChannelMonitorUpdateStatus {
466 pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateStatus {
468 ChannelMonitorUpdateStatus::Completed => nativeChannelMonitorUpdateStatus::Completed,
469 ChannelMonitorUpdateStatus::InProgress => nativeChannelMonitorUpdateStatus::InProgress,
470 ChannelMonitorUpdateStatus::UnrecoverableError => nativeChannelMonitorUpdateStatus::UnrecoverableError,
474 pub(crate) fn into_native(self) -> nativeChannelMonitorUpdateStatus {
476 ChannelMonitorUpdateStatus::Completed => nativeChannelMonitorUpdateStatus::Completed,
477 ChannelMonitorUpdateStatus::InProgress => nativeChannelMonitorUpdateStatus::InProgress,
478 ChannelMonitorUpdateStatus::UnrecoverableError => nativeChannelMonitorUpdateStatus::UnrecoverableError,
482 pub(crate) fn from_native(native: &nativeChannelMonitorUpdateStatus) -> Self {
484 nativeChannelMonitorUpdateStatus::Completed => ChannelMonitorUpdateStatus::Completed,
485 nativeChannelMonitorUpdateStatus::InProgress => ChannelMonitorUpdateStatus::InProgress,
486 nativeChannelMonitorUpdateStatus::UnrecoverableError => ChannelMonitorUpdateStatus::UnrecoverableError,
490 pub(crate) fn native_into(native: nativeChannelMonitorUpdateStatus) -> Self {
492 nativeChannelMonitorUpdateStatus::Completed => ChannelMonitorUpdateStatus::Completed,
493 nativeChannelMonitorUpdateStatus::InProgress => ChannelMonitorUpdateStatus::InProgress,
494 nativeChannelMonitorUpdateStatus::UnrecoverableError => ChannelMonitorUpdateStatus::UnrecoverableError,
498 /// Creates a copy of the ChannelMonitorUpdateStatus
500 pub extern "C" fn ChannelMonitorUpdateStatus_clone(orig: &ChannelMonitorUpdateStatus) -> ChannelMonitorUpdateStatus {
504 /// Utility method to constructs a new Completed-variant ChannelMonitorUpdateStatus
505 pub extern "C" fn ChannelMonitorUpdateStatus_completed() -> ChannelMonitorUpdateStatus {
506 ChannelMonitorUpdateStatus::Completed}
508 /// Utility method to constructs a new InProgress-variant ChannelMonitorUpdateStatus
509 pub extern "C" fn ChannelMonitorUpdateStatus_in_progress() -> ChannelMonitorUpdateStatus {
510 ChannelMonitorUpdateStatus::InProgress}
512 /// Utility method to constructs a new UnrecoverableError-variant ChannelMonitorUpdateStatus
513 pub extern "C" fn ChannelMonitorUpdateStatus_unrecoverable_error() -> ChannelMonitorUpdateStatus {
514 ChannelMonitorUpdateStatus::UnrecoverableError}
515 /// Checks if two ChannelMonitorUpdateStatuss contain equal inner contents.
516 /// This ignores pointers and is_owned flags and looks at the values in fields.
518 pub extern "C" fn ChannelMonitorUpdateStatus_eq(a: &ChannelMonitorUpdateStatus, b: &ChannelMonitorUpdateStatus) -> bool {
519 if &a.to_native() == &b.to_native() { true } else { false }
521 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
522 /// blocks are connected and disconnected.
524 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
525 /// responsible for maintaining a set of monitors such that they can be updated as channel state
526 /// changes. On each update, *all copies* of a [`ChannelMonitor`] must be updated and the update
527 /// persisted to disk to ensure that the latest [`ChannelMonitor`] state can be reloaded if the
528 /// application crashes.
530 /// See method documentation and [`ChannelMonitorUpdateStatus`] for specific requirements.
533 /// An opaque pointer which is passed to your function implementations as an argument.
534 /// This has no meaning in the LDK, and can be NULL or any other value.
535 pub this_arg: *mut c_void,
536 /// Watches a channel identified by `funding_txo` using `monitor`.
538 /// Implementations are responsible for watching the chain for the funding transaction along
539 /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
540 /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
542 /// A return of `Err(())` indicates that the channel should immediately be force-closed without
543 /// broadcasting the funding transaction.
545 /// If the given `funding_txo` has previously been registered via `watch_channel`, `Err(())`
546 /// must be returned.
548 /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
549 /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
550 /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
551 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,
552 /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
554 /// Implementations must call [`ChannelMonitor::update_monitor`] with the given update. This
555 /// may fail (returning an `Err(())`), in which case this should return
556 /// [`ChannelMonitorUpdateStatus::InProgress`] (and the update should never complete). This
557 /// generally implies the channel has been closed (either by the funding outpoint being spent
558 /// on-chain or the [`ChannelMonitor`] having decided to do so and broadcasted a transaction),
559 /// and the [`ChannelManager`] state will be updated once it sees the funding spend on-chain.
561 /// In general, persistence failures should be retried after returning
562 /// [`ChannelMonitorUpdateStatus::InProgress`] and eventually complete. If a failure truly
563 /// cannot be retried, the node should shut down immediately after returning
564 /// [`ChannelMonitorUpdateStatus::UnrecoverableError`], see its documentation for more info.
566 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
567 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,
568 /// Returns any monitor events since the last call. Subsequent calls must only return new
571 /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
572 /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
575 /// For details on asynchronous [`ChannelMonitor`] updating and returning
576 /// [`MonitorEvent::Completed`] here, see [`ChannelMonitorUpdateStatus::InProgress`].
577 pub release_pending_monitor_events: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C3Tuple_OutPointCVec_MonitorEventZPublicKeyZZ,
578 /// Frees any resources associated with this object given its this_arg pointer.
579 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
580 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
582 unsafe impl Send for Watch {}
583 unsafe impl Sync for Watch {}
584 pub(crate) fn Watch_clone_fields(orig: &Watch) -> Watch {
586 this_arg: orig.this_arg,
587 watch_channel: Clone::clone(&orig.watch_channel),
588 update_channel: Clone::clone(&orig.update_channel),
589 release_pending_monitor_events: Clone::clone(&orig.release_pending_monitor_events),
590 free: Clone::clone(&orig.free),
594 use lightning::chain::Watch as rustWatch;
595 impl rustWatch<crate::lightning::sign::WriteableEcdsaChannelSigner> for Watch {
596 fn watch_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut monitor: lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::sign::WriteableEcdsaChannelSigner>) -> Result<lightning::chain::ChannelMonitorUpdateStatus, ()> {
597 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 });
598 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)) })*/ })};
601 fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: &lightning::chain::channelmonitor::ChannelMonitorUpdate) -> lightning::chain::ChannelMonitorUpdateStatus {
602 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 });
605 fn release_pending_monitor_events(&self) -> Vec<(lightning::chain::transaction::OutPoint, Vec<lightning::chain::channelmonitor::MonitorEvent>, Option<bitcoin::secp256k1::PublicKey>)> {
606 let mut ret = (self.release_pending_monitor_events)(self.this_arg);
607 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 }); };
612 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
613 // directly as a Deref trait in higher-level structs:
614 impl core::ops::Deref for Watch {
616 fn deref(&self) -> &Self {
620 impl core::ops::DerefMut for Watch {
621 fn deref_mut(&mut self) -> &mut Self {
625 /// Calls the free function if one is set
627 pub extern "C" fn Watch_free(this_ptr: Watch) { }
628 impl Drop for Watch {
630 if let Some(f) = self.free {
635 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
638 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
639 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
640 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
641 /// receiving full blocks from a chain source, any further filtering is unnecessary.
643 /// After an output has been registered, subsequent block retrievals from the chain source must not
644 /// exclude any transactions matching the new criteria nor any in-block descendants of such
647 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
648 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
649 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
650 /// invocation that has called the `Filter` must return [`InProgress`].
652 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
653 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
654 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
657 /// An opaque pointer which is passed to your function implementations as an argument.
658 /// This has no meaning in the LDK, and can be NULL or any other value.
659 pub this_arg: *mut c_void,
660 /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
661 /// a spending condition.
662 pub register_tx: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32], script_pubkey: crate::c_types::u8slice),
663 /// Registers interest in spends of a transaction output.
665 /// Note that this method might be called during processing of a new block. You therefore need
666 /// to ensure that also dependent output spents within an already connected block are correctly
667 /// handled, e.g., by re-scanning the block in question whenever new outputs have been
668 /// registered mid-processing.
669 pub register_output: extern "C" fn (this_arg: *const c_void, output: crate::lightning::chain::WatchedOutput),
670 /// Frees any resources associated with this object given its this_arg pointer.
671 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
672 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
674 unsafe impl Send for Filter {}
675 unsafe impl Sync for Filter {}
676 pub(crate) fn Filter_clone_fields(orig: &Filter) -> Filter {
678 this_arg: orig.this_arg,
679 register_tx: Clone::clone(&orig.register_tx),
680 register_output: Clone::clone(&orig.register_output),
681 free: Clone::clone(&orig.free),
685 use lightning::chain::Filter as rustFilter;
686 impl rustFilter for Filter {
687 fn register_tx(&self, mut txid: &bitcoin::hash_types::Txid, mut script_pubkey: &bitcoin::blockdata::script::Script) {
688 (self.register_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pubkey[..]))
690 fn register_output(&self, mut output: lightning::chain::WatchedOutput) {
691 (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: ObjOps::heap_alloc(output), is_owned: true })
695 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
696 // directly as a Deref trait in higher-level structs:
697 impl core::ops::Deref for Filter {
699 fn deref(&self) -> &Self {
703 impl core::ops::DerefMut for Filter {
704 fn deref_mut(&mut self) -> &mut Self {
708 /// Calls the free function if one is set
710 pub extern "C" fn Filter_free(this_ptr: Filter) { }
711 impl Drop for Filter {
713 if let Some(f) = self.free {
719 use lightning::chain::WatchedOutput as nativeWatchedOutputImport;
720 pub(crate) type nativeWatchedOutput = nativeWatchedOutputImport;
722 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
724 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
725 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
726 /// [`Confirm::transactions_confirmed`].
728 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
729 /// may have been spent there. See [`Filter::register_output`] for details.
731 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
732 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
735 pub struct WatchedOutput {
736 /// A pointer to the opaque Rust object.
738 /// Nearly everywhere, inner must be non-null, however in places where
739 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
740 pub inner: *mut nativeWatchedOutput,
741 /// Indicates that this is the only struct which contains the same pointer.
743 /// Rust functions which take ownership of an object provided via an argument require
744 /// this to be true and invalidate the object pointed to by inner.
748 impl Drop for WatchedOutput {
750 if self.is_owned && !<*mut nativeWatchedOutput>::is_null(self.inner) {
751 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
755 /// Frees any resources used by the WatchedOutput, if is_owned is set and inner is non-NULL.
757 pub extern "C" fn WatchedOutput_free(this_obj: WatchedOutput) { }
759 /// Used only if an object of this type is returned as a trait impl by a method
760 pub(crate) extern "C" fn WatchedOutput_free_void(this_ptr: *mut c_void) {
761 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeWatchedOutput) };
765 pub(crate) fn get_native_ref(&self) -> &'static nativeWatchedOutput {
766 unsafe { &*ObjOps::untweak_ptr(self.inner) }
768 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeWatchedOutput {
769 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
771 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
772 pub(crate) fn take_inner(mut self) -> *mut nativeWatchedOutput {
773 assert!(self.is_owned);
774 let ret = ObjOps::untweak_ptr(self.inner);
775 self.inner = core::ptr::null_mut();
779 /// First block where the transaction output may have been spent.
781 pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crate::c_types::derived::COption_ThirtyTwoBytesZ {
782 let mut inner_val = &mut this_ptr.get_native_mut_ref().block_hash;
783 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().into_inner() } }) };
786 /// First block where the transaction output may have been spent.
788 pub extern "C" fn WatchedOutput_set_block_hash(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::COption_ThirtyTwoBytesZ) {
789 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() }})} };
790 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.block_hash = local_val;
792 /// Outpoint identifying the transaction output.
794 pub extern "C" fn WatchedOutput_get_outpoint(this_ptr: &WatchedOutput) -> crate::lightning::chain::transaction::OutPoint {
795 let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint;
796 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 }
798 /// Outpoint identifying the transaction output.
800 pub extern "C" fn WatchedOutput_set_outpoint(this_ptr: &mut WatchedOutput, mut val: crate::lightning::chain::transaction::OutPoint) {
801 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
803 /// Spending condition of the transaction output.
805 pub extern "C" fn WatchedOutput_get_script_pubkey(this_ptr: &WatchedOutput) -> crate::c_types::u8slice {
806 let mut inner_val = &mut this_ptr.get_native_mut_ref().script_pubkey;
807 crate::c_types::u8slice::from_slice(&inner_val[..])
809 /// Spending condition of the transaction output.
811 pub extern "C" fn WatchedOutput_set_script_pubkey(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::CVec_u8Z) {
812 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.script_pubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust());
814 /// Constructs a new WatchedOutput given each field
817 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 {
818 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() }})} };
819 WatchedOutput { inner: ObjOps::heap_alloc(nativeWatchedOutput {
820 block_hash: local_block_hash_arg,
821 outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
822 script_pubkey: ::bitcoin::blockdata::script::Script::from(script_pubkey_arg.into_rust()),
825 impl Clone for WatchedOutput {
826 fn clone(&self) -> Self {
828 inner: if <*mut nativeWatchedOutput>::is_null(self.inner) { core::ptr::null_mut() } else {
829 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
835 /// Used only if an object of this type is returned as a trait impl by a method
836 pub(crate) extern "C" fn WatchedOutput_clone_void(this_ptr: *const c_void) -> *mut c_void {
837 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeWatchedOutput)).clone() })) as *mut c_void
840 /// Creates a copy of the WatchedOutput
841 pub extern "C" fn WatchedOutput_clone(orig: &WatchedOutput) -> WatchedOutput {
844 /// Checks if two WatchedOutputs contain equal inner contents.
845 /// This ignores pointers and is_owned flags and looks at the values in fields.
846 /// Two objects with NULL inner values will be considered "equal" here.
848 pub extern "C" fn WatchedOutput_eq(a: &WatchedOutput, b: &WatchedOutput) -> bool {
849 if a.inner == b.inner { return true; }
850 if a.inner.is_null() || b.inner.is_null() { return false; }
851 if a.get_native_ref() == b.get_native_ref() { true } else { false }
853 /// Generates a non-cryptographic 64-bit hash of the WatchedOutput.
855 pub extern "C" fn WatchedOutput_hash(o: &WatchedOutput) -> u64 {
856 if o.inner.is_null() { return 0; }
857 // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
859 let mut hasher = core::hash::SipHasher::new();
860 core::hash::Hash::hash(o.get_native_ref(), &mut hasher);
861 core::hash::Hasher::finish(&hasher)