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 unsafe { let _ = 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 /// Constructs a `BestBlock` that represents the genesis block at height 0 of the given
120 pub extern "C" fn BestBlock_from_genesis(mut network: crate::bitcoin::network::Network) -> BestBlock {
121 let mut ret = lightning::chain::BestBlock::from_genesis(network.into_bitcoin());
122 BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
125 /// Returns a `BestBlock` as identified by the given block hash and height.
128 pub extern "C" fn BestBlock_new(mut block_hash: crate::c_types::ThirtyTwoBytes, mut height: u32) -> BestBlock {
129 let mut ret = lightning::chain::BestBlock::new(::bitcoin::hash_types::BlockHash::from_slice(&block_hash.data[..]).unwrap(), height);
130 BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
133 /// Returns the best block hash.
136 pub extern "C" fn BestBlock_block_hash(this_arg: &BestBlock) -> crate::c_types::ThirtyTwoBytes {
137 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_hash();
138 crate::c_types::ThirtyTwoBytes { data: ret.into_inner() }
141 /// Returns the best block height.
144 pub extern "C" fn BestBlock_height(this_arg: &BestBlock) -> u32 {
145 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.height();
149 /// An error when accessing the chain via [`Access`].
153 pub enum AccessError {
154 /// The requested chain is unknown.
156 /// The requested transaction doesn't exist or hasn't confirmed.
159 use lightning::chain::AccessError as nativeAccessError;
162 pub(crate) fn to_native(&self) -> nativeAccessError {
164 AccessError::UnknownChain => nativeAccessError::UnknownChain,
165 AccessError::UnknownTx => nativeAccessError::UnknownTx,
169 pub(crate) fn into_native(self) -> nativeAccessError {
171 AccessError::UnknownChain => nativeAccessError::UnknownChain,
172 AccessError::UnknownTx => nativeAccessError::UnknownTx,
176 pub(crate) fn from_native(native: &nativeAccessError) -> Self {
178 nativeAccessError::UnknownChain => AccessError::UnknownChain,
179 nativeAccessError::UnknownTx => AccessError::UnknownTx,
183 pub(crate) fn native_into(native: nativeAccessError) -> Self {
185 nativeAccessError::UnknownChain => AccessError::UnknownChain,
186 nativeAccessError::UnknownTx => AccessError::UnknownTx,
190 /// Creates a copy of the AccessError
192 pub extern "C" fn AccessError_clone(orig: &AccessError) -> AccessError {
196 /// Utility method to constructs a new UnknownChain-variant AccessError
197 pub extern "C" fn AccessError_unknown_chain() -> AccessError {
198 AccessError::UnknownChain}
200 /// Utility method to constructs a new UnknownTx-variant AccessError
201 pub extern "C" fn AccessError_unknown_tx() -> AccessError {
202 AccessError::UnknownTx}
203 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
207 /// An opaque pointer which is passed to your function implementations as an argument.
208 /// This has no meaning in the LDK, and can be NULL or any other value.
209 pub this_arg: *mut c_void,
210 /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
211 /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
214 /// [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
216 pub get_utxo: extern "C" fn (this_arg: *const c_void, genesis_hash: *const [u8; 32], short_channel_id: u64) -> crate::c_types::derived::CResult_TxOutAccessErrorZ,
217 /// Frees any resources associated with this object given its this_arg pointer.
218 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
219 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
221 unsafe impl Send for Access {}
222 unsafe impl Sync for Access {}
224 pub(crate) extern "C" fn Access_clone_fields(orig: &Access) -> Access {
226 this_arg: orig.this_arg,
227 get_utxo: Clone::clone(&orig.get_utxo),
228 free: Clone::clone(&orig.free),
232 use lightning::chain::Access as rustAccess;
233 impl rustAccess for Access {
234 fn get_utxo(&self, mut genesis_hash: &bitcoin::hash_types::BlockHash, mut short_channel_id: u64) -> Result<bitcoin::blockdata::transaction::TxOut, lightning::chain::AccessError> {
235 let mut ret = (self.get_utxo)(self.this_arg, genesis_hash.as_inner(), short_channel_id);
236 let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
241 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
242 // directly as a Deref trait in higher-level structs:
243 impl core::ops::Deref for Access {
245 fn deref(&self) -> &Self {
249 /// Calls the free function if one is set
251 pub extern "C" fn Access_free(this_ptr: Access) { }
252 impl Drop for Access {
254 if let Some(f) = self.free {
259 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
262 /// Useful when needing to replay chain data upon startup or as new chain events occur. Clients
263 /// sourcing chain data using a block-oriented API should prefer this interface over [`Confirm`].
264 /// Such clients fetch the entire header chain whereas clients using [`Confirm`] only fetch headers
268 /// An opaque pointer which is passed to your function implementations as an argument.
269 /// This has no meaning in the LDK, and can be NULL or any other value.
270 pub this_arg: *mut c_void,
271 /// Notifies the listener that a block was added at the given height.
272 pub block_connected: extern "C" fn (this_arg: *const c_void, block: crate::c_types::u8slice, height: u32),
273 /// Notifies the listener that a block was removed at the given height.
274 pub block_disconnected: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
275 /// Frees any resources associated with this object given its this_arg pointer.
276 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
277 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
279 unsafe impl Send for Listen {}
280 unsafe impl Sync for Listen {}
282 pub(crate) extern "C" fn Listen_clone_fields(orig: &Listen) -> Listen {
284 this_arg: orig.this_arg,
285 block_connected: Clone::clone(&orig.block_connected),
286 block_disconnected: Clone::clone(&orig.block_disconnected),
287 free: Clone::clone(&orig.free),
291 use lightning::chain::Listen as rustListen;
292 impl rustListen for Listen {
293 fn block_connected(&self, mut block: &bitcoin::blockdata::block::Block, mut height: u32) {
294 let mut local_block = ::bitcoin::consensus::encode::serialize(block);
295 (self.block_connected)(self.this_arg, crate::c_types::u8slice::from_slice(&local_block), height)
297 fn block_disconnected(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
298 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
299 (self.block_disconnected)(self.this_arg, &local_header, height)
303 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
304 // directly as a Deref trait in higher-level structs:
305 impl core::ops::Deref for Listen {
307 fn deref(&self) -> &Self {
311 /// Calls the free function if one is set
313 pub extern "C" fn Listen_free(this_ptr: Listen) { }
314 impl Drop for Listen {
316 if let Some(f) = self.free {
321 /// The `Confirm` trait is used to notify when transactions have been confirmed on chain or
322 /// unconfirmed during a chain reorganization.
324 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
325 /// [`Listen`]. For instance, an Electrum client may implement [`Filter`] by subscribing to activity
326 /// related to registered transactions and outputs. Upon notification, it would pass along the
327 /// matching transactions using this interface.
331 /// The intended use is as follows:
332 /// - Call [`transactions_confirmed`] to process any on-chain activity of interest.
333 /// - Call [`transaction_unconfirmed`] to process any transaction returned by [`get_relevant_txids`]
334 /// that has been reorganized out of the chain.
335 /// - Call [`best_block_updated`] whenever a new chain tip becomes available.
339 /// Clients must call these methods in chain order. Specifically:
340 /// - Transactions confirmed in a block must be given before transactions confirmed in a later
342 /// - Dependent transactions within the same block must be given in topological order, possibly in
344 /// - Unconfirmed transactions must be given after the original confirmations and before any
347 /// See individual method documentation for further details.
349 /// [`transactions_confirmed`]: Self::transactions_confirmed
350 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
351 /// [`best_block_updated`]: Self::best_block_updated
352 /// [`get_relevant_txids`]: Self::get_relevant_txids
355 /// An opaque pointer which is passed to your function implementations as an argument.
356 /// This has no meaning in the LDK, and can be NULL or any other value.
357 pub this_arg: *mut c_void,
358 /// Processes transactions confirmed in a block with a given header and height.
360 /// Should be called for any transactions registered by [`Filter::register_tx`] or any
361 /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
362 /// appearing in the same block do not need to be included in the same call; instead, multiple
363 /// calls with additional transactions may be made so long as they are made in [chain order].
365 /// May be called before or after [`best_block_updated`] for the corresponding block. However,
366 /// in the event of a chain reorganization, it must not be called with a `header` that is no
367 /// longer in the chain as of the last call to [`best_block_updated`].
369 /// [chain order]: Confirm#Order
370 /// [`best_block_updated`]: Self::best_block_updated
371 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),
372 /// Processes a transaction that is no longer confirmed as result of a chain reorganization.
374 /// Should be called for any transaction returned by [`get_relevant_txids`] if it has been
375 /// reorganized out of the best chain. Once called, the given transaction should not be returned
376 /// by [`get_relevant_txids`] unless it has been reconfirmed via [`transactions_confirmed`].
378 /// [`get_relevant_txids`]: Self::get_relevant_txids
379 /// [`transactions_confirmed`]: Self::transactions_confirmed
380 pub transaction_unconfirmed: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32]),
381 /// Processes an update to the best header connected at the given height.
383 /// Should be called when a new header is available but may be skipped for intermediary blocks
384 /// if they become available at the same time.
385 pub best_block_updated: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
386 /// Returns transactions that should be monitored for reorganization out of the chain.
388 /// Should include any transactions passed to [`transactions_confirmed`] that have insufficient
389 /// confirmations to be safe from a chain reorganization. Should not include any transactions
390 /// passed to [`transaction_unconfirmed`] unless later reconfirmed.
392 /// May be called to determine the subset of transactions that must still be monitored for
393 /// reorganization. Will be idempotent between calls but may change as a result of calls to the
394 /// other interface methods. Thus, this is useful to determine which transactions may need to be
395 /// given to [`transaction_unconfirmed`].
397 /// [`transactions_confirmed`]: Self::transactions_confirmed
398 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
400 pub get_relevant_txids: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_TxidZ,
401 /// Frees any resources associated with this object given its this_arg pointer.
402 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
403 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
405 unsafe impl Send for Confirm {}
406 unsafe impl Sync for Confirm {}
408 pub(crate) extern "C" fn Confirm_clone_fields(orig: &Confirm) -> Confirm {
410 this_arg: orig.this_arg,
411 transactions_confirmed: Clone::clone(&orig.transactions_confirmed),
412 transaction_unconfirmed: Clone::clone(&orig.transaction_unconfirmed),
413 best_block_updated: Clone::clone(&orig.best_block_updated),
414 get_relevant_txids: Clone::clone(&orig.get_relevant_txids),
415 free: Clone::clone(&orig.free),
419 use lightning::chain::Confirm as rustConfirm;
420 impl rustConfirm for Confirm {
421 fn transactions_confirmed(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
422 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
423 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 }); };
424 (self.transactions_confirmed)(self.this_arg, &local_header, local_txdata.into(), height)
426 fn transaction_unconfirmed(&self, mut txid: &bitcoin::hash_types::Txid) {
427 (self.transaction_unconfirmed)(self.this_arg, txid.as_inner())
429 fn best_block_updated(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
430 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
431 (self.best_block_updated)(self.this_arg, &local_header, height)
433 fn get_relevant_txids(&self) -> Vec<bitcoin::hash_types::Txid> {
434 let mut ret = (self.get_relevant_txids)(self.this_arg);
435 let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { ::bitcoin::hash_types::Txid::from_slice(&item.data[..]).unwrap() }); };
440 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
441 // directly as a Deref trait in higher-level structs:
442 impl core::ops::Deref for Confirm {
444 fn deref(&self) -> &Self {
448 /// Calls the free function if one is set
450 pub extern "C" fn Confirm_free(this_ptr: Confirm) { }
451 impl Drop for Confirm {
453 if let Some(f) = self.free {
458 /// An error enum representing a failure to persist a channel monitor update.
462 pub enum ChannelMonitorUpdateErr {
463 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
464 /// our state failed, but is expected to succeed at some point in the future).
466 /// Such a failure will \"freeze\" a channel, preventing us from revoking old states or
467 /// submitting new commitment transactions to the counterparty. Once the update(s) that failed
468 /// have been successfully applied, a [`MonitorEvent::UpdateCompleted`] event should be returned
469 /// via [`Watch::release_pending_monitor_events`] which will then restore the channel to an
470 /// operational state.
472 /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
473 /// you return a TemporaryFailure you must ensure that it is written to disk safely before
474 /// writing out the latest ChannelManager state.
476 /// Even when a channel has been \"frozen\" updates to the ChannelMonitor can continue to occur
477 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
478 /// to claim it on this channel) and those updates must be applied wherever they can be. At
479 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
480 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
481 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
484 /// Note that even if updates made after TemporaryFailure succeed you must still provide a
485 /// [`MonitorEvent::UpdateCompleted`] to ensure you have the latest monitor and re-enable
486 /// normal channel operation. Note that this is normally generated through a call to
487 /// [`ChainMonitor::channel_monitor_updated`].
489 /// Note that the update being processed here will not be replayed for you when you return a
490 /// [`MonitorEvent::UpdateCompleted`] event via [`Watch::release_pending_monitor_events`], so
491 /// you must store the update itself on your own local disk prior to returning a
492 /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
493 /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
496 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
497 /// remote location (with local copies persisted immediately), it is anticipated that all
498 /// updates will return TemporaryFailure until the remote copies could be updated.
500 /// [`ChainMonitor::channel_monitor_updated`]: chainmonitor::ChainMonitor::channel_monitor_updated
502 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
503 /// different watchtower and cannot update with all watchtowers that were previously informed
504 /// of this channel).
506 /// At reception of this error, ChannelManager will force-close the channel and return at
507 /// least a final ChannelMonitorUpdate::ChannelForceClosed which must be delivered to at
508 /// least one ChannelMonitor copy. Revocation secret MUST NOT be released and offchain channel
509 /// update must be rejected.
511 /// This failure may also signal a failure to update the local persisted copy of one of
512 /// the channel monitor instance.
514 /// Note that even when you fail a holder commitment transaction update, you must store the
515 /// update to ensure you can claim from it in case of a duplicate copy of this ChannelMonitor
516 /// broadcasts it (e.g distributed channel-monitor deployment)
518 /// In case of distributed watchtowers deployment, the new version must be written to disk, as
519 /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
520 /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
521 /// lagging behind on block processing.
524 use lightning::chain::ChannelMonitorUpdateErr as nativeChannelMonitorUpdateErr;
525 impl ChannelMonitorUpdateErr {
527 pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateErr {
529 ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
530 ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
534 pub(crate) fn into_native(self) -> nativeChannelMonitorUpdateErr {
536 ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
537 ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
541 pub(crate) fn from_native(native: &nativeChannelMonitorUpdateErr) -> Self {
543 nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
544 nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
548 pub(crate) fn native_into(native: nativeChannelMonitorUpdateErr) -> Self {
550 nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
551 nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
555 /// Creates a copy of the ChannelMonitorUpdateErr
557 pub extern "C" fn ChannelMonitorUpdateErr_clone(orig: &ChannelMonitorUpdateErr) -> ChannelMonitorUpdateErr {
561 /// Utility method to constructs a new TemporaryFailure-variant ChannelMonitorUpdateErr
562 pub extern "C" fn ChannelMonitorUpdateErr_temporary_failure() -> ChannelMonitorUpdateErr {
563 ChannelMonitorUpdateErr::TemporaryFailure}
565 /// Utility method to constructs a new PermanentFailure-variant ChannelMonitorUpdateErr
566 pub extern "C" fn ChannelMonitorUpdateErr_permanent_failure() -> ChannelMonitorUpdateErr {
567 ChannelMonitorUpdateErr::PermanentFailure}
568 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
569 /// blocks are connected and disconnected.
571 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
572 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
573 /// channel state changes and HTLCs are resolved. See method documentation for specific
576 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
577 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
578 /// without taking any further action such as persisting the current state.
580 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
581 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
582 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
583 /// funds in the channel. See [`ChannelMonitorUpdateErr`] for more details about how to handle
584 /// multiple instances.
586 /// [`PermanentFailure`]: ChannelMonitorUpdateErr::PermanentFailure
589 /// An opaque pointer which is passed to your function implementations as an argument.
590 /// This has no meaning in the LDK, and can be NULL or any other value.
591 pub this_arg: *mut c_void,
592 /// Watches a channel identified by `funding_txo` using `monitor`.
594 /// Implementations are responsible for watching the chain for the funding transaction along
595 /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
596 /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
598 /// Note: this interface MUST error with `ChannelMonitorUpdateErr::PermanentFailure` if
599 /// the given `funding_txo` has previously been registered via `watch_channel`.
601 /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
602 /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
603 /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
605 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_NoneChannelMonitorUpdateErrZ,
606 /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
608 /// Implementations must call [`update_monitor`] with the given update. See
609 /// [`ChannelMonitorUpdateErr`] for invariants around returning an error.
611 /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
613 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::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ,
614 /// Returns any monitor events since the last call. Subsequent calls must only return new
617 /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
618 /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
621 /// For details on asynchronous [`ChannelMonitor`] updating and returning
622 /// [`MonitorEvent::UpdateCompleted`] here, see [`ChannelMonitorUpdateErr::TemporaryFailure`].
624 pub release_pending_monitor_events: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_MonitorEventZ,
625 /// Frees any resources associated with this object given its this_arg pointer.
626 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
627 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
629 unsafe impl Send for Watch {}
630 unsafe impl Sync for Watch {}
632 pub(crate) extern "C" fn Watch_clone_fields(orig: &Watch) -> Watch {
634 this_arg: orig.this_arg,
635 watch_channel: Clone::clone(&orig.watch_channel),
636 update_channel: Clone::clone(&orig.update_channel),
637 release_pending_monitor_events: Clone::clone(&orig.release_pending_monitor_events),
638 free: Clone::clone(&orig.free),
642 use lightning::chain::Watch as rustWatch;
643 impl rustWatch<crate::lightning::chain::keysinterface::Sign> for Watch {
644 fn watch_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut monitor: lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::chain::keysinterface::Sign>) -> Result<(), lightning::chain::ChannelMonitorUpdateErr> {
645 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 });
646 let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
649 fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: lightning::chain::channelmonitor::ChannelMonitorUpdate) -> Result<(), lightning::chain::ChannelMonitorUpdateErr> {
650 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: ObjOps::heap_alloc(update), is_owned: true });
651 let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
654 fn release_pending_monitor_events(&self) -> Vec<lightning::chain::channelmonitor::MonitorEvent> {
655 let mut ret = (self.release_pending_monitor_events)(self.this_arg);
656 let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { item.into_native() }); };
661 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
662 // directly as a Deref trait in higher-level structs:
663 impl core::ops::Deref for Watch {
665 fn deref(&self) -> &Self {
669 /// Calls the free function if one is set
671 pub extern "C" fn Watch_free(this_ptr: Watch) { }
672 impl Drop for Watch {
674 if let Some(f) = self.free {
679 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
682 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
683 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
684 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
685 /// receiving full blocks from a chain source, any further filtering is unnecessary.
687 /// After an output has been registered, subsequent block retrievals from the chain source must not
688 /// exclude any transactions matching the new criteria nor any in-block descendants of such
691 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
692 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
693 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
694 /// invocation that has called the `Filter` must return [`TemporaryFailure`].
696 /// [`TemporaryFailure`]: ChannelMonitorUpdateErr::TemporaryFailure
697 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
698 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
701 /// An opaque pointer which is passed to your function implementations as an argument.
702 /// This has no meaning in the LDK, and can be NULL or any other value.
703 pub this_arg: *mut c_void,
704 /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
705 /// a spending condition.
706 pub register_tx: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32], script_pubkey: crate::c_types::u8slice),
707 /// Registers interest in spends of a transaction output.
709 /// Optionally, when `output.block_hash` is set, should return any transaction spending the
710 /// output that is found in the corresponding block along with its index.
712 /// This return value is useful for Electrum clients in order to supply in-block descendant
713 /// transactions which otherwise were not included. This is not necessary for other clients if
714 /// such descendant transactions were already included (e.g., when a BIP 157 client provides the
717 pub register_output: extern "C" fn (this_arg: *const c_void, output: crate::lightning::chain::WatchedOutput) -> crate::c_types::derived::COption_C2Tuple_usizeTransactionZZ,
718 /// Frees any resources associated with this object given its this_arg pointer.
719 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
720 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
722 unsafe impl Send for Filter {}
723 unsafe impl Sync for Filter {}
725 pub(crate) extern "C" fn Filter_clone_fields(orig: &Filter) -> Filter {
727 this_arg: orig.this_arg,
728 register_tx: Clone::clone(&orig.register_tx),
729 register_output: Clone::clone(&orig.register_output),
730 free: Clone::clone(&orig.free),
734 use lightning::chain::Filter as rustFilter;
735 impl rustFilter for Filter {
736 fn register_tx(&self, mut txid: &bitcoin::hash_types::Txid, mut script_pubkey: &bitcoin::blockdata::script::Script) {
737 (self.register_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pubkey[..]))
739 fn register_output(&self, mut output: lightning::chain::WatchedOutput) -> Option<(usize, bitcoin::blockdata::transaction::Transaction)> {
740 let mut ret = (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: ObjOps::heap_alloc(output), is_owned: true });
741 let mut local_ret = if ret.is_some() { Some( { let (mut orig_ret_0_0, mut orig_ret_0_1) = ret.take().to_rust(); let mut local_ret_0 = (orig_ret_0_0, orig_ret_0_1.into_bitcoin()); local_ret_0 }) } else { None };
746 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
747 // directly as a Deref trait in higher-level structs:
748 impl core::ops::Deref for Filter {
750 fn deref(&self) -> &Self {
754 /// Calls the free function if one is set
756 pub extern "C" fn Filter_free(this_ptr: Filter) { }
757 impl Drop for Filter {
759 if let Some(f) = self.free {
765 use lightning::chain::WatchedOutput as nativeWatchedOutputImport;
766 pub(crate) type nativeWatchedOutput = nativeWatchedOutputImport;
768 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
770 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
771 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
772 /// the return value of [`Filter::register_output`].
774 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
775 /// may have been spent there. See [`Filter::register_output`] for details.
777 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
778 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
781 pub struct WatchedOutput {
782 /// A pointer to the opaque Rust object.
784 /// Nearly everywhere, inner must be non-null, however in places where
785 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
786 pub inner: *mut nativeWatchedOutput,
787 /// Indicates that this is the only struct which contains the same pointer.
789 /// Rust functions which take ownership of an object provided via an argument require
790 /// this to be true and invalidate the object pointed to by inner.
794 impl Drop for WatchedOutput {
796 if self.is_owned && !<*mut nativeWatchedOutput>::is_null(self.inner) {
797 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
801 /// Frees any resources used by the WatchedOutput, if is_owned is set and inner is non-NULL.
803 pub extern "C" fn WatchedOutput_free(this_obj: WatchedOutput) { }
805 /// Used only if an object of this type is returned as a trait impl by a method
806 pub(crate) extern "C" fn WatchedOutput_free_void(this_ptr: *mut c_void) {
807 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeWatchedOutput); }
811 pub(crate) fn get_native_ref(&self) -> &'static nativeWatchedOutput {
812 unsafe { &*ObjOps::untweak_ptr(self.inner) }
814 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeWatchedOutput {
815 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
817 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
818 pub(crate) fn take_inner(mut self) -> *mut nativeWatchedOutput {
819 assert!(self.is_owned);
820 let ret = ObjOps::untweak_ptr(self.inner);
821 self.inner = core::ptr::null_mut();
825 /// First block where the transaction output may have been spent.
827 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
829 pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crate::c_types::ThirtyTwoBytes {
830 let mut inner_val = &mut this_ptr.get_native_mut_ref().block_hash;
831 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() } } };
834 /// First block where the transaction output may have been spent.
836 /// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
838 pub extern "C" fn WatchedOutput_set_block_hash(this_ptr: &mut WatchedOutput, mut val: crate::c_types::ThirtyTwoBytes) {
839 let mut local_val = if val.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap() }) };
840 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.block_hash = local_val;
842 /// Outpoint identifying the transaction output.
844 pub extern "C" fn WatchedOutput_get_outpoint(this_ptr: &WatchedOutput) -> crate::lightning::chain::transaction::OutPoint {
845 let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint;
846 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 }
848 /// Outpoint identifying the transaction output.
850 pub extern "C" fn WatchedOutput_set_outpoint(this_ptr: &mut WatchedOutput, mut val: crate::lightning::chain::transaction::OutPoint) {
851 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
853 /// Spending condition of the transaction output.
855 pub extern "C" fn WatchedOutput_get_script_pubkey(this_ptr: &WatchedOutput) -> crate::c_types::u8slice {
856 let mut inner_val = &mut this_ptr.get_native_mut_ref().script_pubkey;
857 crate::c_types::u8slice::from_slice(&inner_val[..])
859 /// Spending condition of the transaction output.
861 pub extern "C" fn WatchedOutput_set_script_pubkey(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::CVec_u8Z) {
862 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.script_pubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust());
864 /// Constructs a new WatchedOutput given each field
867 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 {
868 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() }) };
869 WatchedOutput { inner: ObjOps::heap_alloc(nativeWatchedOutput {
870 block_hash: local_block_hash_arg,
871 outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
872 script_pubkey: ::bitcoin::blockdata::script::Script::from(script_pubkey_arg.into_rust()),
875 impl Clone for WatchedOutput {
876 fn clone(&self) -> Self {
878 inner: if <*mut nativeWatchedOutput>::is_null(self.inner) { core::ptr::null_mut() } else {
879 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
885 /// Used only if an object of this type is returned as a trait impl by a method
886 pub(crate) extern "C" fn WatchedOutput_clone_void(this_ptr: *const c_void) -> *mut c_void {
887 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeWatchedOutput)).clone() })) as *mut c_void
890 /// Creates a copy of the WatchedOutput
891 pub extern "C" fn WatchedOutput_clone(orig: &WatchedOutput) -> WatchedOutput {
894 /// Checks if two WatchedOutputs contain equal inner contents.
896 pub extern "C" fn WatchedOutput_hash(o: &WatchedOutput) -> u64 {
897 if o.inner.is_null() { return 0; }
898 // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
900 let mut hasher = core::hash::SipHasher::new();
901 core::hash::Hash::hash(o.get_native_ref(), &mut hasher);
902 core::hash::Hasher::finish(&hasher)