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 core::ffi::c_void;
13 use core::convert::Infallible;
14 use bitcoin::hashes::Hash;
15 use crate::c_types::*;
16 #[cfg(feature="no-std")]
17 use alloc::{vec::Vec, boxed::Box};
19 pub mod chaininterface;
21 pub mod channelmonitor;
23 pub mod keysinterface;
26 use alloc::str::FromStr;
27 use core::ffi::c_void;
28 use core::convert::Infallible;
29 use bitcoin::hashes::Hash;
30 use crate::c_types::*;
31 #[cfg(feature="no-std")]
32 use alloc::{vec::Vec, boxed::Box};
37 use alloc::str::FromStr;
38 use core::ffi::c_void;
39 use core::convert::Infallible;
40 use bitcoin::hashes::Hash;
41 use crate::c_types::*;
42 #[cfg(feature="no-std")]
43 use alloc::{vec::Vec, boxed::Box};
47 use lightning::chain::BestBlock as nativeBestBlockImport;
48 pub(crate) type nativeBestBlock = nativeBestBlockImport;
50 /// The best known block as identified by its hash and height.
53 pub struct BestBlock {
54 /// A pointer to the opaque Rust object.
56 /// Nearly everywhere, inner must be non-null, however in places where
57 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
58 pub inner: *mut nativeBestBlock,
59 /// Indicates that this is the only struct which contains the same pointer.
61 /// Rust functions which take ownership of an object provided via an argument require
62 /// this to be true and invalidate the object pointed to by inner.
66 impl Drop for BestBlock {
68 if self.is_owned && !<*mut nativeBestBlock>::is_null(self.inner) {
69 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
73 /// Frees any resources used by the BestBlock, if is_owned is set and inner is non-NULL.
75 pub extern "C" fn BestBlock_free(this_obj: BestBlock) { }
77 /// Used only if an object of this type is returned as a trait impl by a method
78 pub(crate) extern "C" fn BestBlock_free_void(this_ptr: *mut c_void) {
79 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeBestBlock) };
83 pub(crate) fn get_native_ref(&self) -> &'static nativeBestBlock {
84 unsafe { &*ObjOps::untweak_ptr(self.inner) }
86 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBestBlock {
87 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
89 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
90 pub(crate) fn take_inner(mut self) -> *mut nativeBestBlock {
91 assert!(self.is_owned);
92 let ret = ObjOps::untweak_ptr(self.inner);
93 self.inner = core::ptr::null_mut();
97 impl Clone for BestBlock {
98 fn clone(&self) -> Self {
100 inner: if <*mut nativeBestBlock>::is_null(self.inner) { core::ptr::null_mut() } else {
101 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
107 /// Used only if an object of this type is returned as a trait impl by a method
108 pub(crate) extern "C" fn BestBlock_clone_void(this_ptr: *const c_void) -> *mut c_void {
109 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeBestBlock)).clone() })) as *mut c_void
112 /// Creates a copy of the BestBlock
113 pub extern "C" fn BestBlock_clone(orig: &BestBlock) -> BestBlock {
116 /// Checks if two BestBlocks contain equal inner contents.
117 /// This ignores pointers and is_owned flags and looks at the values in fields.
118 /// Two objects with NULL inner values will be considered "equal" here.
120 pub extern "C" fn BestBlock_eq(a: &BestBlock, b: &BestBlock) -> bool {
121 if a.inner == b.inner { return true; }
122 if a.inner.is_null() || b.inner.is_null() { return false; }
123 if a.get_native_ref() == b.get_native_ref() { true } else { false }
125 /// Constructs a `BestBlock` that represents the genesis block at height 0 of the given
129 pub extern "C" fn BestBlock_from_network(mut network: crate::bitcoin::network::Network) -> crate::lightning::chain::BestBlock {
130 let mut ret = lightning::chain::BestBlock::from_network(network.into_bitcoin());
131 crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
134 /// Returns a `BestBlock` as identified by the given block hash and height.
137 pub extern "C" fn BestBlock_new(mut block_hash: crate::c_types::ThirtyTwoBytes, mut height: u32) -> crate::lightning::chain::BestBlock {
138 let mut ret = lightning::chain::BestBlock::new(::bitcoin::hash_types::BlockHash::from_slice(&block_hash.data[..]).unwrap(), height);
139 crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
142 /// Returns the best block hash.
145 pub extern "C" fn BestBlock_block_hash(this_arg: &crate::lightning::chain::BestBlock) -> crate::c_types::ThirtyTwoBytes {
146 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_hash();
147 crate::c_types::ThirtyTwoBytes { data: ret.into_inner() }
150 /// Returns the best block height.
153 pub extern "C" fn BestBlock_height(this_arg: &crate::lightning::chain::BestBlock) -> u32 {
154 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.height();
158 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
161 /// Useful when needing to replay chain data upon startup or as new chain events occur. Clients
162 /// sourcing chain data using a block-oriented API should prefer this interface over [`Confirm`].
163 /// Such clients fetch the entire header chain whereas clients using [`Confirm`] only fetch headers
166 /// By using [`Listen::filtered_block_connected`] this interface supports clients fetching the
167 /// entire header chain and only blocks with matching transaction data using BIP 157 filters or
168 /// other similar filtering.
171 /// An opaque pointer which is passed to your function implementations as an argument.
172 /// This has no meaning in the LDK, and can be NULL or any other value.
173 pub this_arg: *mut c_void,
174 /// Notifies the listener that a block was added at the given height, with the transaction data
175 /// possibly filtered.
176 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),
177 /// Notifies the listener that a block was added at the given height.
178 pub block_connected: extern "C" fn (this_arg: *const c_void, block: crate::c_types::u8slice, height: u32),
179 /// Notifies the listener that a block was removed at the given height.
180 pub block_disconnected: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
181 /// Frees any resources associated with this object given its this_arg pointer.
182 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
183 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
185 unsafe impl Send for Listen {}
186 unsafe impl Sync for Listen {}
188 pub(crate) extern "C" fn Listen_clone_fields(orig: &Listen) -> Listen {
190 this_arg: orig.this_arg,
191 filtered_block_connected: Clone::clone(&orig.filtered_block_connected),
192 block_connected: Clone::clone(&orig.block_connected),
193 block_disconnected: Clone::clone(&orig.block_disconnected),
194 free: Clone::clone(&orig.free),
198 use lightning::chain::Listen as rustListen;
199 impl rustListen for Listen {
200 fn filtered_block_connected(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
201 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
202 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 }); };
203 (self.filtered_block_connected)(self.this_arg, &local_header, local_txdata.into(), height)
205 fn block_connected(&self, mut block: &bitcoin::blockdata::block::Block, mut height: u32) {
206 let mut local_block = ::bitcoin::consensus::encode::serialize(block);
207 (self.block_connected)(self.this_arg, crate::c_types::u8slice::from_slice(&local_block), height)
209 fn block_disconnected(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
210 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
211 (self.block_disconnected)(self.this_arg, &local_header, height)
215 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
216 // directly as a Deref trait in higher-level structs:
217 impl core::ops::Deref for Listen {
219 fn deref(&self) -> &Self {
223 /// Calls the free function if one is set
225 pub extern "C" fn Listen_free(this_ptr: Listen) { }
226 impl Drop for Listen {
228 if let Some(f) = self.free {
233 /// The `Confirm` trait is used to notify LDK when relevant transactions have been confirmed on
234 /// chain or unconfirmed during a chain reorganization.
236 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
237 /// [`Listen`]. For instance, an Electrum-based transaction sync implementation may implement
238 /// [`Filter`] to subscribe to relevant transactions and unspent outputs it should monitor for
239 /// on-chain activity. Then, it needs to notify LDK via this interface upon observing any changes
240 /// with reference to the confirmation status of the monitored objects.
243 /// The intended use is as follows:
244 /// - Call [`transactions_confirmed`] to notify LDK whenever any of the registered transactions or
245 /// outputs are, respectively, confirmed or spent on chain.
246 /// - Call [`transaction_unconfirmed`] to notify LDK whenever any transaction returned by
247 /// [`get_relevant_txids`] is no longer confirmed in the block with the given block hash.
248 /// - Call [`best_block_updated`] to notify LDK whenever a new chain tip becomes available.
252 /// Clients must call these methods in chain order. Specifically:
253 /// - Transactions which are confirmed in a particular block must be given before transactions
254 /// confirmed in a later block.
255 /// - Dependent transactions within the same block must be given in topological order, possibly in
257 /// - All unconfirmed transactions must be given after the original confirmations and before *any*
258 /// reconfirmations, i.e., [`transactions_confirmed`] and [`transaction_unconfirmed`] calls should
259 /// never be interleaved, but always conduced *en bloc*.
260 /// - Any reconfirmed transactions need to be explicitly unconfirmed before they are reconfirmed
261 /// in regard to the new block.
263 /// See individual method documentation for further details.
265 /// [`transactions_confirmed`]: Self::transactions_confirmed
266 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
267 /// [`best_block_updated`]: Self::best_block_updated
268 /// [`get_relevant_txids`]: Self::get_relevant_txids
271 /// An opaque pointer which is passed to your function implementations as an argument.
272 /// This has no meaning in the LDK, and can be NULL or any other value.
273 pub this_arg: *mut c_void,
274 /// Notifies LDK of transactions confirmed in a block with a given header and height.
276 /// Must be called for any transactions registered by [`Filter::register_tx`] or any
277 /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
278 /// appearing in the same block do not need to be included in the same call; instead, multiple
279 /// calls with additional transactions may be made so long as they are made in [chain order].
281 /// May be called before or after [`best_block_updated`] for the corresponding block. However,
282 /// in the event of a chain reorganization, it must not be called with a `header` that is no
283 /// longer in the chain as of the last call to [`best_block_updated`].
285 /// [chain order]: Confirm#order
286 /// [`best_block_updated`]: Self::best_block_updated
287 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),
288 /// Notifies LDK of a transaction that is no longer confirmed as result of a chain reorganization.
290 /// Must be called for any transaction returned by [`get_relevant_txids`] if it has been
291 /// reorganized out of the best chain or if it is no longer confirmed in the block with the
292 /// given block hash. Once called, the given transaction will not be returned
293 /// by [`get_relevant_txids`], unless it has been reconfirmed via [`transactions_confirmed`].
295 /// [`get_relevant_txids`]: Self::get_relevant_txids
296 /// [`transactions_confirmed`]: Self::transactions_confirmed
297 pub transaction_unconfirmed: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32]),
298 /// Notifies LDK of an update to the best header connected at the given height.
300 /// Must be called whenever a new chain tip becomes available. May be skipped for intermediary
302 pub best_block_updated: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
303 /// Returns transactions that must be monitored for reorganization out of the chain along
304 /// with the hash of the block as part of which it had been previously confirmed.
306 /// Note that the returned `Option<BlockHash>` might be `None` for channels created with LDK
307 /// 0.0.112 and prior, in which case you need to manually track previous confirmations.
309 /// Will include any transactions passed to [`transactions_confirmed`] that have insufficient
310 /// confirmations to be safe from a chain reorganization. Will not include any transactions
311 /// passed to [`transaction_unconfirmed`], unless later reconfirmed.
313 /// Must be called to determine the subset of transactions that must be monitored for
314 /// reorganization. Will be idempotent between calls but may change as a result of calls to the
315 /// other interface methods. Thus, this is useful to determine which transactions must be
316 /// given to [`transaction_unconfirmed`].
318 /// If any of the returned transactions are confirmed in a block other than the one with the
319 /// given hash, they need to be unconfirmed and reconfirmed via [`transaction_unconfirmed`] and
320 /// [`transactions_confirmed`], respectively.
322 /// [`transactions_confirmed`]: Self::transactions_confirmed
323 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
325 pub get_relevant_txids: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C2Tuple_TxidBlockHashZZ,
326 /// Frees any resources associated with this object given its this_arg pointer.
327 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
328 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
330 unsafe impl Send for Confirm {}
331 unsafe impl Sync for Confirm {}
333 pub(crate) extern "C" fn Confirm_clone_fields(orig: &Confirm) -> Confirm {
335 this_arg: orig.this_arg,
336 transactions_confirmed: Clone::clone(&orig.transactions_confirmed),
337 transaction_unconfirmed: Clone::clone(&orig.transaction_unconfirmed),
338 best_block_updated: Clone::clone(&orig.best_block_updated),
339 get_relevant_txids: Clone::clone(&orig.get_relevant_txids),
340 free: Clone::clone(&orig.free),
344 use lightning::chain::Confirm as rustConfirm;
345 impl rustConfirm for Confirm {
346 fn transactions_confirmed(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
347 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
348 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 }); };
349 (self.transactions_confirmed)(self.this_arg, &local_header, local_txdata.into(), height)
351 fn transaction_unconfirmed(&self, mut txid: &bitcoin::hash_types::Txid) {
352 (self.transaction_unconfirmed)(self.this_arg, txid.as_inner())
354 fn best_block_updated(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
355 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
356 (self.best_block_updated)(self.this_arg, &local_header, height)
358 fn get_relevant_txids(&self) -> Vec<(bitcoin::hash_types::Txid, Option<bitcoin::hash_types::BlockHash>)> {
359 let mut ret = (self.get_relevant_txids)(self.this_arg);
360 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 = if orig_ret_0_1.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&orig_ret_0_1.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 }); };
365 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
366 // directly as a Deref trait in higher-level structs:
367 impl core::ops::Deref for Confirm {
369 fn deref(&self) -> &Self {
373 /// Calls the free function if one is set
375 pub extern "C" fn Confirm_free(this_ptr: Confirm) { }
376 impl Drop for Confirm {
378 if let Some(f) = self.free {
383 /// An enum representing the status of a channel monitor update persistence.
387 pub enum ChannelMonitorUpdateStatus {
388 /// The update has been durably persisted and all copies of the relevant [`ChannelMonitor`]
389 /// have been updated.
391 /// This includes performing any `fsync()` calls required to ensure the update is guaranteed to
392 /// be available on restart even if the application crashes.
394 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
395 /// our state failed, but is expected to succeed at some point in the future).
397 /// Such a failure will \"freeze\" a channel, preventing us from revoking old states or
398 /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
399 /// have been successfully applied, a [`MonitorEvent::Completed`] can be used to restore the
400 /// channel to an operational state.
402 /// Note that a given [`ChannelManager`] will *never* re-generate a [`ChannelMonitorUpdate`].
403 /// If you return this error you must ensure that it is written to disk safely before writing
404 /// the latest [`ChannelManager`] state, or you should return [`PermanentFailure`] instead.
406 /// Even when a channel has been \"frozen\", updates to the [`ChannelMonitor`] can continue to
407 /// occur (e.g. if an inbound HTLC which we forwarded was claimed upstream, resulting in us
408 /// attempting to claim it on this channel) and those updates must still be persisted.
410 /// No updates to the channel will be made which could invalidate other [`ChannelMonitor`]s
411 /// until a [`MonitorEvent::Completed`] is provided, even if you return no error on a later
412 /// monitor update for the same channel.
414 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
415 /// remote location (with local copies persisted immediately), it is anticipated that all
416 /// updates will return [`InProgress`] until the remote copies could be updated.
418 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
419 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
420 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
422 /// Used to indicate no further channel monitor updates will be allowed (likely a disk failure
423 /// or a remote copy of this [`ChannelMonitor`] is no longer reachable and thus not updatable).
425 /// When this is returned, [`ChannelManager`] will force-close the channel but *not* broadcast
426 /// our current commitment transaction. This avoids a dangerous case where a local disk failure
427 /// (e.g. the Linux-default remounting of the disk as read-only) causes [`PermanentFailure`]s
428 /// for all monitor updates. If we were to broadcast our latest commitment transaction and then
429 /// restart, we could end up reading a previous [`ChannelMonitor`] and [`ChannelManager`],
430 /// revoking our now-broadcasted state before seeing it confirm and losing all our funds.
432 /// Note that this is somewhat of a tradeoff - if the disk is really gone and we may have lost
433 /// the data permanently, we really should broadcast immediately. If the data can be recovered
434 /// with manual intervention, we'd rather close the channel, rejecting future updates to it,
435 /// and broadcast the latest state only if we have HTLCs to claim which are timing out (which
436 /// we do as long as blocks are connected).
438 /// In order to broadcast the latest local commitment transaction, you'll need to call
439 /// [`ChannelMonitor::get_latest_holder_commitment_txn`] and broadcast the resulting
440 /// transactions once you've safely ensured no further channel updates can be generated by your
441 /// [`ChannelManager`].
443 /// Note that at least one final [`ChannelMonitorUpdate`] may still be provided, which must
444 /// still be processed by a running [`ChannelMonitor`]. This final update will mark the
445 /// [`ChannelMonitor`] as finalized, ensuring no further updates (e.g. revocation of the latest
446 /// commitment transaction) are allowed.
448 /// Note that even if you return a [`PermanentFailure`] due to unavailability of secondary
449 /// [`ChannelMonitor`] copies, you should still make an attempt to store the update where
450 /// possible to ensure you can claim HTLC outputs on the latest commitment transaction
451 /// broadcasted later.
453 /// In case of distributed watchtowers deployment, the new version must be written to disk, as
454 /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
455 /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
456 /// lagging behind on block processing.
458 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
459 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
462 use lightning::chain::ChannelMonitorUpdateStatus as ChannelMonitorUpdateStatusImport;
463 pub(crate) type nativeChannelMonitorUpdateStatus = ChannelMonitorUpdateStatusImport;
465 impl ChannelMonitorUpdateStatus {
467 pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateStatus {
469 ChannelMonitorUpdateStatus::Completed => nativeChannelMonitorUpdateStatus::Completed,
470 ChannelMonitorUpdateStatus::InProgress => nativeChannelMonitorUpdateStatus::InProgress,
471 ChannelMonitorUpdateStatus::PermanentFailure => nativeChannelMonitorUpdateStatus::PermanentFailure,
475 pub(crate) fn into_native(self) -> nativeChannelMonitorUpdateStatus {
477 ChannelMonitorUpdateStatus::Completed => nativeChannelMonitorUpdateStatus::Completed,
478 ChannelMonitorUpdateStatus::InProgress => nativeChannelMonitorUpdateStatus::InProgress,
479 ChannelMonitorUpdateStatus::PermanentFailure => nativeChannelMonitorUpdateStatus::PermanentFailure,
483 pub(crate) fn from_native(native: &nativeChannelMonitorUpdateStatus) -> Self {
485 nativeChannelMonitorUpdateStatus::Completed => ChannelMonitorUpdateStatus::Completed,
486 nativeChannelMonitorUpdateStatus::InProgress => ChannelMonitorUpdateStatus::InProgress,
487 nativeChannelMonitorUpdateStatus::PermanentFailure => ChannelMonitorUpdateStatus::PermanentFailure,
491 pub(crate) fn native_into(native: nativeChannelMonitorUpdateStatus) -> Self {
493 nativeChannelMonitorUpdateStatus::Completed => ChannelMonitorUpdateStatus::Completed,
494 nativeChannelMonitorUpdateStatus::InProgress => ChannelMonitorUpdateStatus::InProgress,
495 nativeChannelMonitorUpdateStatus::PermanentFailure => ChannelMonitorUpdateStatus::PermanentFailure,
499 /// Creates a copy of the ChannelMonitorUpdateStatus
501 pub extern "C" fn ChannelMonitorUpdateStatus_clone(orig: &ChannelMonitorUpdateStatus) -> ChannelMonitorUpdateStatus {
505 /// Utility method to constructs a new Completed-variant ChannelMonitorUpdateStatus
506 pub extern "C" fn ChannelMonitorUpdateStatus_completed() -> ChannelMonitorUpdateStatus {
507 ChannelMonitorUpdateStatus::Completed}
509 /// Utility method to constructs a new InProgress-variant ChannelMonitorUpdateStatus
510 pub extern "C" fn ChannelMonitorUpdateStatus_in_progress() -> ChannelMonitorUpdateStatus {
511 ChannelMonitorUpdateStatus::InProgress}
513 /// Utility method to constructs a new PermanentFailure-variant ChannelMonitorUpdateStatus
514 pub extern "C" fn ChannelMonitorUpdateStatus_permanent_failure() -> ChannelMonitorUpdateStatus {
515 ChannelMonitorUpdateStatus::PermanentFailure}
516 /// Checks if two ChannelMonitorUpdateStatuss contain equal inner contents.
517 /// This ignores pointers and is_owned flags and looks at the values in fields.
519 pub extern "C" fn ChannelMonitorUpdateStatus_eq(a: &ChannelMonitorUpdateStatus, b: &ChannelMonitorUpdateStatus) -> bool {
520 if &a.to_native() == &b.to_native() { true } else { false }
522 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
523 /// blocks are connected and disconnected.
525 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
526 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
527 /// channel state changes and HTLCs are resolved. See method documentation for specific
530 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
531 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
532 /// without taking any further action such as persisting the current state.
534 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
535 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
536 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
537 /// funds in the channel. See [`ChannelMonitorUpdateStatus`] for more details about how to handle
538 /// multiple instances.
540 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
543 /// An opaque pointer which is passed to your function implementations as an argument.
544 /// This has no meaning in the LDK, and can be NULL or any other value.
545 pub this_arg: *mut c_void,
546 /// Watches a channel identified by `funding_txo` using `monitor`.
548 /// Implementations are responsible for watching the chain for the funding transaction along
549 /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
550 /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
552 /// Note: this interface MUST error with [`ChannelMonitorUpdateStatus::PermanentFailure`] if
553 /// the given `funding_txo` has previously been registered via `watch_channel`.
555 /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
556 /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
557 /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
559 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::lightning::chain::ChannelMonitorUpdateStatus,
560 /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
562 /// Implementations must call [`update_monitor`] with the given update. See
563 /// [`ChannelMonitorUpdateStatus`] for invariants around returning an error.
565 /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
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`].
578 pub release_pending_monitor_events: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C3Tuple_OutPointCVec_MonitorEventZPublicKeyZZ,
579 /// Frees any resources associated with this object given its this_arg pointer.
580 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
581 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
583 unsafe impl Send for Watch {}
584 unsafe impl Sync for Watch {}
586 pub(crate) extern "C" fn Watch_clone_fields(orig: &Watch) -> Watch {
588 this_arg: orig.this_arg,
589 watch_channel: Clone::clone(&orig.watch_channel),
590 update_channel: Clone::clone(&orig.update_channel),
591 release_pending_monitor_events: Clone::clone(&orig.release_pending_monitor_events),
592 free: Clone::clone(&orig.free),
596 use lightning::chain::Watch as rustWatch;
597 impl rustWatch<crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner> for Watch {
598 fn watch_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut monitor: lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner>) -> lightning::chain::ChannelMonitorUpdateStatus {
599 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 });
602 fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: &lightning::chain::channelmonitor::ChannelMonitorUpdate) -> lightning::chain::ChannelMonitorUpdateStatus {
603 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 });
606 fn release_pending_monitor_events(&self) -> Vec<(lightning::chain::transaction::OutPoint, Vec<lightning::chain::channelmonitor::MonitorEvent>, Option<bitcoin::secp256k1::PublicKey>)> {
607 let mut ret = (self.release_pending_monitor_events)(self.this_arg);
608 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 }); };
613 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
614 // directly as a Deref trait in higher-level structs:
615 impl core::ops::Deref for Watch {
617 fn deref(&self) -> &Self {
621 /// Calls the free function if one is set
623 pub extern "C" fn Watch_free(this_ptr: Watch) { }
624 impl Drop for Watch {
626 if let Some(f) = self.free {
631 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
634 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
635 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
636 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
637 /// receiving full blocks from a chain source, any further filtering is unnecessary.
639 /// After an output has been registered, subsequent block retrievals from the chain source must not
640 /// exclude any transactions matching the new criteria nor any in-block descendants of such
643 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
644 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
645 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
646 /// invocation that has called the `Filter` must return [`InProgress`].
648 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
649 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
650 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
653 /// An opaque pointer which is passed to your function implementations as an argument.
654 /// This has no meaning in the LDK, and can be NULL or any other value.
655 pub this_arg: *mut c_void,
656 /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
657 /// a spending condition.
658 pub register_tx: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32], script_pubkey: crate::c_types::u8slice),
659 /// Registers interest in spends of a transaction output.
661 /// Note that this method might be called during processing of a new block. You therefore need
662 /// to ensure that also dependent output spents within an already connected block are correctly
663 /// handled, e.g., by re-scanning the block in question whenever new outputs have been
664 /// registered mid-processing.
665 pub register_output: extern "C" fn (this_arg: *const c_void, output: crate::lightning::chain::WatchedOutput),
666 /// Frees any resources associated with this object given its this_arg pointer.
667 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
668 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
670 unsafe impl Send for Filter {}
671 unsafe impl Sync for Filter {}
673 pub(crate) extern "C" fn Filter_clone_fields(orig: &Filter) -> Filter {
675 this_arg: orig.this_arg,
676 register_tx: Clone::clone(&orig.register_tx),
677 register_output: Clone::clone(&orig.register_output),
678 free: Clone::clone(&orig.free),
682 use lightning::chain::Filter as rustFilter;
683 impl rustFilter for Filter {
684 fn register_tx(&self, mut txid: &bitcoin::hash_types::Txid, mut script_pubkey: &bitcoin::blockdata::script::Script) {
685 (self.register_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pubkey[..]))
687 fn register_output(&self, mut output: lightning::chain::WatchedOutput) {
688 (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: ObjOps::heap_alloc(output), is_owned: true })
692 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
693 // directly as a Deref trait in higher-level structs:
694 impl core::ops::Deref for Filter {
696 fn deref(&self) -> &Self {
700 /// Calls the free function if one is set
702 pub extern "C" fn Filter_free(this_ptr: Filter) { }
703 impl Drop for Filter {
705 if let Some(f) = self.free {
711 use lightning::chain::WatchedOutput as nativeWatchedOutputImport;
712 pub(crate) type nativeWatchedOutput = nativeWatchedOutputImport;
714 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
716 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
717 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
718 /// [`Confirm::transactions_confirmed`].
720 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
721 /// may have been spent there. See [`Filter::register_output`] for details.
723 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
724 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
727 pub struct WatchedOutput {
728 /// A pointer to the opaque Rust object.
730 /// Nearly everywhere, inner must be non-null, however in places where
731 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
732 pub inner: *mut nativeWatchedOutput,
733 /// Indicates that this is the only struct which contains the same pointer.
735 /// Rust functions which take ownership of an object provided via an argument require
736 /// this to be true and invalidate the object pointed to by inner.
740 impl Drop for WatchedOutput {
742 if self.is_owned && !<*mut nativeWatchedOutput>::is_null(self.inner) {
743 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
747 /// Frees any resources used by the WatchedOutput, if is_owned is set and inner is non-NULL.
749 pub extern "C" fn WatchedOutput_free(this_obj: WatchedOutput) { }
751 /// Used only if an object of this type is returned as a trait impl by a method
752 pub(crate) extern "C" fn WatchedOutput_free_void(this_ptr: *mut c_void) {
753 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeWatchedOutput) };
757 pub(crate) fn get_native_ref(&self) -> &'static nativeWatchedOutput {
758 unsafe { &*ObjOps::untweak_ptr(self.inner) }
760 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeWatchedOutput {
761 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
763 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
764 pub(crate) fn take_inner(mut self) -> *mut nativeWatchedOutput {
765 assert!(self.is_owned);
766 let ret = ObjOps::untweak_ptr(self.inner);
767 self.inner = core::ptr::null_mut();
771 /// First block where the transaction output may have been spent.
773 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
775 pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crate::c_types::ThirtyTwoBytes {
776 let mut inner_val = &mut this_ptr.get_native_mut_ref().block_hash;
777 let mut local_inner_val = if inner_val.is_none() { crate::c_types::ThirtyTwoBytes::null() } else { { crate::c_types::ThirtyTwoBytes { data: (inner_val.unwrap()).into_inner() } } };
780 /// First block where the transaction output may have been spent.
782 /// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
784 pub extern "C" fn WatchedOutput_set_block_hash(this_ptr: &mut WatchedOutput, mut val: crate::c_types::ThirtyTwoBytes) {
785 let mut local_val = if val.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap() }) };
786 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.block_hash = local_val;
788 /// Outpoint identifying the transaction output.
790 pub extern "C" fn WatchedOutput_get_outpoint(this_ptr: &WatchedOutput) -> crate::lightning::chain::transaction::OutPoint {
791 let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint;
792 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 }
794 /// Outpoint identifying the transaction output.
796 pub extern "C" fn WatchedOutput_set_outpoint(this_ptr: &mut WatchedOutput, mut val: crate::lightning::chain::transaction::OutPoint) {
797 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
799 /// Spending condition of the transaction output.
801 pub extern "C" fn WatchedOutput_get_script_pubkey(this_ptr: &WatchedOutput) -> crate::c_types::u8slice {
802 let mut inner_val = &mut this_ptr.get_native_mut_ref().script_pubkey;
803 crate::c_types::u8slice::from_slice(&inner_val[..])
805 /// Spending condition of the transaction output.
807 pub extern "C" fn WatchedOutput_set_script_pubkey(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::CVec_u8Z) {
808 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.script_pubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust());
810 /// Constructs a new WatchedOutput given each field
813 pub extern "C" fn WatchedOutput_new(mut block_hash_arg: crate::c_types::ThirtyTwoBytes, mut outpoint_arg: crate::lightning::chain::transaction::OutPoint, mut script_pubkey_arg: crate::c_types::derived::CVec_u8Z) -> WatchedOutput {
814 let mut local_block_hash_arg = if block_hash_arg.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&block_hash_arg.data[..]).unwrap() }) };
815 WatchedOutput { inner: ObjOps::heap_alloc(nativeWatchedOutput {
816 block_hash: local_block_hash_arg,
817 outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
818 script_pubkey: ::bitcoin::blockdata::script::Script::from(script_pubkey_arg.into_rust()),
821 impl Clone for WatchedOutput {
822 fn clone(&self) -> Self {
824 inner: if <*mut nativeWatchedOutput>::is_null(self.inner) { core::ptr::null_mut() } else {
825 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
831 /// Used only if an object of this type is returned as a trait impl by a method
832 pub(crate) extern "C" fn WatchedOutput_clone_void(this_ptr: *const c_void) -> *mut c_void {
833 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeWatchedOutput)).clone() })) as *mut c_void
836 /// Creates a copy of the WatchedOutput
837 pub extern "C" fn WatchedOutput_clone(orig: &WatchedOutput) -> WatchedOutput {
840 /// Checks if two WatchedOutputs contain equal inner contents.
841 /// This ignores pointers and is_owned flags and looks at the values in fields.
842 /// Two objects with NULL inner values will be considered "equal" here.
844 pub extern "C" fn WatchedOutput_eq(a: &WatchedOutput, b: &WatchedOutput) -> bool {
845 if a.inner == b.inner { return true; }
846 if a.inner.is_null() || b.inner.is_null() { return false; }
847 if a.get_native_ref() == b.get_native_ref() { true } else { false }
849 /// Generates a non-cryptographic 64-bit hash of the WatchedOutput.
851 pub extern "C" fn WatchedOutput_hash(o: &WatchedOutput) -> u64 {
852 if o.inner.is_null() { return 0; }
853 // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
855 let mut hasher = core::hash::SipHasher::new();
856 core::hash::Hash::hash(o.get_native_ref(), &mut hasher);
857 core::hash::Hasher::finish(&hasher)