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) -> crate::lightning::chain::BestBlock {
121 let mut ret = lightning::chain::BestBlock::from_genesis(network.into_bitcoin());
122 crate::lightning::chain::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) -> crate::lightning::chain::BestBlock {
129 let mut ret = lightning::chain::BestBlock::new(::bitcoin::hash_types::BlockHash::from_slice(&block_hash.data[..]).unwrap(), height);
130 crate::lightning::chain::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: &crate::lightning::chain::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: &crate::lightning::chain::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 AccessErrorImport;
160 pub(crate) type nativeAccessError = AccessErrorImport;
164 pub(crate) fn to_native(&self) -> nativeAccessError {
166 AccessError::UnknownChain => nativeAccessError::UnknownChain,
167 AccessError::UnknownTx => nativeAccessError::UnknownTx,
171 pub(crate) fn into_native(self) -> nativeAccessError {
173 AccessError::UnknownChain => nativeAccessError::UnknownChain,
174 AccessError::UnknownTx => nativeAccessError::UnknownTx,
178 pub(crate) fn from_native(native: &nativeAccessError) -> Self {
180 nativeAccessError::UnknownChain => AccessError::UnknownChain,
181 nativeAccessError::UnknownTx => AccessError::UnknownTx,
185 pub(crate) fn native_into(native: nativeAccessError) -> Self {
187 nativeAccessError::UnknownChain => AccessError::UnknownChain,
188 nativeAccessError::UnknownTx => AccessError::UnknownTx,
192 /// Creates a copy of the AccessError
194 pub extern "C" fn AccessError_clone(orig: &AccessError) -> AccessError {
198 /// Utility method to constructs a new UnknownChain-variant AccessError
199 pub extern "C" fn AccessError_unknown_chain() -> AccessError {
200 AccessError::UnknownChain}
202 /// Utility method to constructs a new UnknownTx-variant AccessError
203 pub extern "C" fn AccessError_unknown_tx() -> AccessError {
204 AccessError::UnknownTx}
205 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
209 /// An opaque pointer which is passed to your function implementations as an argument.
210 /// This has no meaning in the LDK, and can be NULL or any other value.
211 pub this_arg: *mut c_void,
212 /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
213 /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
216 /// [`short_channel_id`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#definition-of-short_channel_id
218 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,
219 /// Frees any resources associated with this object given its this_arg pointer.
220 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
221 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
223 unsafe impl Send for Access {}
224 unsafe impl Sync for Access {}
226 pub(crate) extern "C" fn Access_clone_fields(orig: &Access) -> Access {
228 this_arg: orig.this_arg,
229 get_utxo: Clone::clone(&orig.get_utxo),
230 free: Clone::clone(&orig.free),
234 use lightning::chain::Access as rustAccess;
235 impl rustAccess for Access {
236 fn get_utxo(&self, mut genesis_hash: &bitcoin::hash_types::BlockHash, mut short_channel_id: u64) -> Result<bitcoin::blockdata::transaction::TxOut, lightning::chain::AccessError> {
237 let mut ret = (self.get_utxo)(self.this_arg, genesis_hash.as_inner(), short_channel_id);
238 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() })};
243 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
244 // directly as a Deref trait in higher-level structs:
245 impl core::ops::Deref for Access {
247 fn deref(&self) -> &Self {
251 /// Calls the free function if one is set
253 pub extern "C" fn Access_free(this_ptr: Access) { }
254 impl Drop for Access {
256 if let Some(f) = self.free {
261 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
264 /// Useful when needing to replay chain data upon startup or as new chain events occur. Clients
265 /// sourcing chain data using a block-oriented API should prefer this interface over [`Confirm`].
266 /// Such clients fetch the entire header chain whereas clients using [`Confirm`] only fetch headers
269 /// By using [`Listen::filtered_block_connected`] this interface supports clients fetching the
270 /// entire header chain and only blocks with matching transaction data using BIP 157 filters or
271 /// other similar filtering.
274 /// An opaque pointer which is passed to your function implementations as an argument.
275 /// This has no meaning in the LDK, and can be NULL or any other value.
276 pub this_arg: *mut c_void,
277 /// Notifies the listener that a block was added at the given height, with the transaction data
278 /// possibly filtered.
279 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),
280 /// Notifies the listener that a block was added at the given height.
281 pub block_connected: extern "C" fn (this_arg: *const c_void, block: crate::c_types::u8slice, height: u32),
282 /// Notifies the listener that a block was removed at the given height.
283 pub block_disconnected: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
284 /// Frees any resources associated with this object given its this_arg pointer.
285 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
286 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
288 unsafe impl Send for Listen {}
289 unsafe impl Sync for Listen {}
291 pub(crate) extern "C" fn Listen_clone_fields(orig: &Listen) -> Listen {
293 this_arg: orig.this_arg,
294 filtered_block_connected: Clone::clone(&orig.filtered_block_connected),
295 block_connected: Clone::clone(&orig.block_connected),
296 block_disconnected: Clone::clone(&orig.block_disconnected),
297 free: Clone::clone(&orig.free),
301 use lightning::chain::Listen as rustListen;
302 impl rustListen for Listen {
303 fn filtered_block_connected(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
304 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
305 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 }); };
306 (self.filtered_block_connected)(self.this_arg, &local_header, local_txdata.into(), height)
308 fn block_connected(&self, mut block: &bitcoin::blockdata::block::Block, mut height: u32) {
309 let mut local_block = ::bitcoin::consensus::encode::serialize(block);
310 (self.block_connected)(self.this_arg, crate::c_types::u8slice::from_slice(&local_block), height)
312 fn block_disconnected(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
313 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
314 (self.block_disconnected)(self.this_arg, &local_header, height)
318 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
319 // directly as a Deref trait in higher-level structs:
320 impl core::ops::Deref for Listen {
322 fn deref(&self) -> &Self {
326 /// Calls the free function if one is set
328 pub extern "C" fn Listen_free(this_ptr: Listen) { }
329 impl Drop for Listen {
331 if let Some(f) = self.free {
336 /// The `Confirm` trait is used to notify when transactions have been confirmed on chain or
337 /// unconfirmed during a chain reorganization.
339 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
340 /// [`Listen`]. For instance, an Electrum client may implement [`Filter`] by subscribing to activity
341 /// related to registered transactions and outputs. Upon notification, it would pass along the
342 /// matching transactions using this interface.
346 /// The intended use is as follows:
347 /// - Call [`transactions_confirmed`] to process any on-chain activity of interest.
348 /// - Call [`transaction_unconfirmed`] to process any transaction returned by [`get_relevant_txids`]
349 /// that has been reorganized out of the chain.
350 /// - Call [`best_block_updated`] whenever a new chain tip becomes available.
354 /// Clients must call these methods in chain order. Specifically:
355 /// - Transactions confirmed in a block must be given before transactions confirmed in a later
357 /// - Dependent transactions within the same block must be given in topological order, possibly in
359 /// - Unconfirmed transactions must be given after the original confirmations and before any
362 /// See individual method documentation for further details.
364 /// [`transactions_confirmed`]: Self::transactions_confirmed
365 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
366 /// [`best_block_updated`]: Self::best_block_updated
367 /// [`get_relevant_txids`]: Self::get_relevant_txids
370 /// An opaque pointer which is passed to your function implementations as an argument.
371 /// This has no meaning in the LDK, and can be NULL or any other value.
372 pub this_arg: *mut c_void,
373 /// Processes transactions confirmed in a block with a given header and height.
375 /// Should be called for any transactions registered by [`Filter::register_tx`] or any
376 /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
377 /// appearing in the same block do not need to be included in the same call; instead, multiple
378 /// calls with additional transactions may be made so long as they are made in [chain order].
380 /// May be called before or after [`best_block_updated`] for the corresponding block. However,
381 /// in the event of a chain reorganization, it must not be called with a `header` that is no
382 /// longer in the chain as of the last call to [`best_block_updated`].
384 /// [chain order]: Confirm#Order
385 /// [`best_block_updated`]: Self::best_block_updated
386 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),
387 /// Processes a transaction that is no longer confirmed as result of a chain reorganization.
389 /// Should be called for any transaction returned by [`get_relevant_txids`] if it has been
390 /// reorganized out of the best chain. Once called, the given transaction should not be returned
391 /// by [`get_relevant_txids`] unless it has been reconfirmed via [`transactions_confirmed`].
393 /// [`get_relevant_txids`]: Self::get_relevant_txids
394 /// [`transactions_confirmed`]: Self::transactions_confirmed
395 pub transaction_unconfirmed: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32]),
396 /// Processes an update to the best header connected at the given height.
398 /// Should be called when a new header is available but may be skipped for intermediary blocks
399 /// if they become available at the same time.
400 pub best_block_updated: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
401 /// Returns transactions that should be monitored for reorganization out of the chain.
403 /// Should include any transactions passed to [`transactions_confirmed`] that have insufficient
404 /// confirmations to be safe from a chain reorganization. Should not include any transactions
405 /// passed to [`transaction_unconfirmed`] unless later reconfirmed.
407 /// May be called to determine the subset of transactions that must still be monitored for
408 /// reorganization. Will be idempotent between calls but may change as a result of calls to the
409 /// other interface methods. Thus, this is useful to determine which transactions may need to be
410 /// given to [`transaction_unconfirmed`].
412 /// [`transactions_confirmed`]: Self::transactions_confirmed
413 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
415 pub get_relevant_txids: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_TxidZ,
416 /// Frees any resources associated with this object given its this_arg pointer.
417 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
418 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
420 unsafe impl Send for Confirm {}
421 unsafe impl Sync for Confirm {}
423 pub(crate) extern "C" fn Confirm_clone_fields(orig: &Confirm) -> Confirm {
425 this_arg: orig.this_arg,
426 transactions_confirmed: Clone::clone(&orig.transactions_confirmed),
427 transaction_unconfirmed: Clone::clone(&orig.transaction_unconfirmed),
428 best_block_updated: Clone::clone(&orig.best_block_updated),
429 get_relevant_txids: Clone::clone(&orig.get_relevant_txids),
430 free: Clone::clone(&orig.free),
434 use lightning::chain::Confirm as rustConfirm;
435 impl rustConfirm for Confirm {
436 fn transactions_confirmed(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
437 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
438 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 }); };
439 (self.transactions_confirmed)(self.this_arg, &local_header, local_txdata.into(), height)
441 fn transaction_unconfirmed(&self, mut txid: &bitcoin::hash_types::Txid) {
442 (self.transaction_unconfirmed)(self.this_arg, txid.as_inner())
444 fn best_block_updated(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
445 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
446 (self.best_block_updated)(self.this_arg, &local_header, height)
448 fn get_relevant_txids(&self) -> Vec<bitcoin::hash_types::Txid> {
449 let mut ret = (self.get_relevant_txids)(self.this_arg);
450 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() }); };
455 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
456 // directly as a Deref trait in higher-level structs:
457 impl core::ops::Deref for Confirm {
459 fn deref(&self) -> &Self {
463 /// Calls the free function if one is set
465 pub extern "C" fn Confirm_free(this_ptr: Confirm) { }
466 impl Drop for Confirm {
468 if let Some(f) = self.free {
473 /// An error enum representing a failure to persist a channel monitor update.
477 pub enum ChannelMonitorUpdateErr {
478 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
479 /// our state failed, but is expected to succeed at some point in the future).
481 /// Such a failure will \"freeze\" a channel, preventing us from revoking old states or
482 /// submitting new commitment transactions to the counterparty. Once the update(s) that failed
483 /// have been successfully applied, a [`MonitorEvent::UpdateCompleted`] event should be returned
484 /// via [`Watch::release_pending_monitor_events`] which will then restore the channel to an
485 /// operational state.
487 /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
488 /// you return a TemporaryFailure you must ensure that it is written to disk safely before
489 /// writing out the latest ChannelManager state.
491 /// Even when a channel has been \"frozen\" updates to the ChannelMonitor can continue to occur
492 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
493 /// to claim it on this channel) and those updates must be applied wherever they can be. At
494 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
495 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
496 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
499 /// Note that even if updates made after TemporaryFailure succeed you must still provide a
500 /// [`MonitorEvent::UpdateCompleted`] to ensure you have the latest monitor and re-enable
501 /// normal channel operation. Note that this is normally generated through a call to
502 /// [`ChainMonitor::channel_monitor_updated`].
504 /// Note that the update being processed here will not be replayed for you when you return a
505 /// [`MonitorEvent::UpdateCompleted`] event via [`Watch::release_pending_monitor_events`], so
506 /// you must store the update itself on your own local disk prior to returning a
507 /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
508 /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
511 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
512 /// remote location (with local copies persisted immediately), it is anticipated that all
513 /// updates will return TemporaryFailure until the remote copies could be updated.
515 /// [`ChainMonitor::channel_monitor_updated`]: chainmonitor::ChainMonitor::channel_monitor_updated
517 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
518 /// different watchtower and cannot update with all watchtowers that were previously informed
519 /// of this channel).
521 /// At reception of this error, ChannelManager will force-close the channel and return at
522 /// least a final ChannelMonitorUpdate::ChannelForceClosed which must be delivered to at
523 /// least one ChannelMonitor copy. Revocation secret MUST NOT be released and offchain channel
524 /// update must be rejected.
526 /// This failure may also signal a failure to update the local persisted copy of one of
527 /// the channel monitor instance.
529 /// Note that even when you fail a holder commitment transaction update, you must store the
530 /// update to ensure you can claim from it in case of a duplicate copy of this ChannelMonitor
531 /// broadcasts it (e.g distributed channel-monitor deployment)
533 /// In case of distributed watchtowers deployment, the new version must be written to disk, as
534 /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
535 /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
536 /// lagging behind on block processing.
539 use lightning::chain::ChannelMonitorUpdateErr as ChannelMonitorUpdateErrImport;
540 pub(crate) type nativeChannelMonitorUpdateErr = ChannelMonitorUpdateErrImport;
542 impl ChannelMonitorUpdateErr {
544 pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateErr {
546 ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
547 ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
551 pub(crate) fn into_native(self) -> nativeChannelMonitorUpdateErr {
553 ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
554 ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
558 pub(crate) fn from_native(native: &nativeChannelMonitorUpdateErr) -> Self {
560 nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
561 nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
565 pub(crate) fn native_into(native: nativeChannelMonitorUpdateErr) -> Self {
567 nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
568 nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
572 /// Creates a copy of the ChannelMonitorUpdateErr
574 pub extern "C" fn ChannelMonitorUpdateErr_clone(orig: &ChannelMonitorUpdateErr) -> ChannelMonitorUpdateErr {
578 /// Utility method to constructs a new TemporaryFailure-variant ChannelMonitorUpdateErr
579 pub extern "C" fn ChannelMonitorUpdateErr_temporary_failure() -> ChannelMonitorUpdateErr {
580 ChannelMonitorUpdateErr::TemporaryFailure}
582 /// Utility method to constructs a new PermanentFailure-variant ChannelMonitorUpdateErr
583 pub extern "C" fn ChannelMonitorUpdateErr_permanent_failure() -> ChannelMonitorUpdateErr {
584 ChannelMonitorUpdateErr::PermanentFailure}
585 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
586 /// blocks are connected and disconnected.
588 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
589 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
590 /// channel state changes and HTLCs are resolved. See method documentation for specific
593 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
594 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
595 /// without taking any further action such as persisting the current state.
597 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
598 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
599 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
600 /// funds in the channel. See [`ChannelMonitorUpdateErr`] for more details about how to handle
601 /// multiple instances.
603 /// [`PermanentFailure`]: ChannelMonitorUpdateErr::PermanentFailure
606 /// An opaque pointer which is passed to your function implementations as an argument.
607 /// This has no meaning in the LDK, and can be NULL or any other value.
608 pub this_arg: *mut c_void,
609 /// Watches a channel identified by `funding_txo` using `monitor`.
611 /// Implementations are responsible for watching the chain for the funding transaction along
612 /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
613 /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
615 /// Note: this interface MUST error with `ChannelMonitorUpdateErr::PermanentFailure` if
616 /// the given `funding_txo` has previously been registered via `watch_channel`.
618 /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
619 /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
620 /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
622 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,
623 /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
625 /// Implementations must call [`update_monitor`] with the given update. See
626 /// [`ChannelMonitorUpdateErr`] for invariants around returning an error.
628 /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
630 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,
631 /// Returns any monitor events since the last call. Subsequent calls must only return new
634 /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
635 /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
638 /// For details on asynchronous [`ChannelMonitor`] updating and returning
639 /// [`MonitorEvent::UpdateCompleted`] here, see [`ChannelMonitorUpdateErr::TemporaryFailure`].
641 pub release_pending_monitor_events: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C2Tuple_OutPointCVec_MonitorEventZZZ,
642 /// Frees any resources associated with this object given its this_arg pointer.
643 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
644 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
646 unsafe impl Send for Watch {}
647 unsafe impl Sync for Watch {}
649 pub(crate) extern "C" fn Watch_clone_fields(orig: &Watch) -> Watch {
651 this_arg: orig.this_arg,
652 watch_channel: Clone::clone(&orig.watch_channel),
653 update_channel: Clone::clone(&orig.update_channel),
654 release_pending_monitor_events: Clone::clone(&orig.release_pending_monitor_events),
655 free: Clone::clone(&orig.free),
659 use lightning::chain::Watch as rustWatch;
660 impl rustWatch<crate::lightning::chain::keysinterface::Sign> for Watch {
661 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> {
662 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 });
663 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() })};
666 fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: lightning::chain::channelmonitor::ChannelMonitorUpdate) -> Result<(), lightning::chain::ChannelMonitorUpdateErr> {
667 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 });
668 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() })};
671 fn release_pending_monitor_events(&self) -> Vec<(lightning::chain::transaction::OutPoint, Vec<lightning::chain::channelmonitor::MonitorEvent>)> {
672 let mut ret = (self.release_pending_monitor_events)(self.this_arg);
673 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 = 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_ret_0 = (*unsafe { Box::from_raw(orig_ret_0_0.take_inner()) }, local_orig_ret_0_1); local_ret_0 }); };
678 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
679 // directly as a Deref trait in higher-level structs:
680 impl core::ops::Deref for Watch {
682 fn deref(&self) -> &Self {
686 /// Calls the free function if one is set
688 pub extern "C" fn Watch_free(this_ptr: Watch) { }
689 impl Drop for Watch {
691 if let Some(f) = self.free {
696 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
699 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
700 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
701 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
702 /// receiving full blocks from a chain source, any further filtering is unnecessary.
704 /// After an output has been registered, subsequent block retrievals from the chain source must not
705 /// exclude any transactions matching the new criteria nor any in-block descendants of such
708 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
709 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
710 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
711 /// invocation that has called the `Filter` must return [`TemporaryFailure`].
713 /// [`TemporaryFailure`]: ChannelMonitorUpdateErr::TemporaryFailure
714 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
715 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
718 /// An opaque pointer which is passed to your function implementations as an argument.
719 /// This has no meaning in the LDK, and can be NULL or any other value.
720 pub this_arg: *mut c_void,
721 /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
722 /// a spending condition.
723 pub register_tx: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32], script_pubkey: crate::c_types::u8slice),
724 /// Registers interest in spends of a transaction output.
726 /// Optionally, when `output.block_hash` is set, should return any transaction spending the
727 /// output that is found in the corresponding block along with its index.
729 /// This return value is useful for Electrum clients in order to supply in-block descendant
730 /// transactions which otherwise were not included. This is not necessary for other clients if
731 /// such descendant transactions were already included (e.g., when a BIP 157 client provides the
734 pub register_output: extern "C" fn (this_arg: *const c_void, output: crate::lightning::chain::WatchedOutput) -> crate::c_types::derived::COption_C2Tuple_usizeTransactionZZ,
735 /// Frees any resources associated with this object given its this_arg pointer.
736 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
737 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
739 unsafe impl Send for Filter {}
740 unsafe impl Sync for Filter {}
742 pub(crate) extern "C" fn Filter_clone_fields(orig: &Filter) -> Filter {
744 this_arg: orig.this_arg,
745 register_tx: Clone::clone(&orig.register_tx),
746 register_output: Clone::clone(&orig.register_output),
747 free: Clone::clone(&orig.free),
751 use lightning::chain::Filter as rustFilter;
752 impl rustFilter for Filter {
753 fn register_tx(&self, mut txid: &bitcoin::hash_types::Txid, mut script_pubkey: &bitcoin::blockdata::script::Script) {
754 (self.register_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pubkey[..]))
756 fn register_output(&self, mut output: lightning::chain::WatchedOutput) -> Option<(usize, bitcoin::blockdata::transaction::Transaction)> {
757 let mut ret = (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: ObjOps::heap_alloc(output), is_owned: true });
758 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 };
763 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
764 // directly as a Deref trait in higher-level structs:
765 impl core::ops::Deref for Filter {
767 fn deref(&self) -> &Self {
771 /// Calls the free function if one is set
773 pub extern "C" fn Filter_free(this_ptr: Filter) { }
774 impl Drop for Filter {
776 if let Some(f) = self.free {
782 use lightning::chain::WatchedOutput as nativeWatchedOutputImport;
783 pub(crate) type nativeWatchedOutput = nativeWatchedOutputImport;
785 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
787 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
788 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
789 /// the return value of [`Filter::register_output`].
791 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
792 /// may have been spent there. See [`Filter::register_output`] for details.
794 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
795 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
798 pub struct WatchedOutput {
799 /// A pointer to the opaque Rust object.
801 /// Nearly everywhere, inner must be non-null, however in places where
802 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
803 pub inner: *mut nativeWatchedOutput,
804 /// Indicates that this is the only struct which contains the same pointer.
806 /// Rust functions which take ownership of an object provided via an argument require
807 /// this to be true and invalidate the object pointed to by inner.
811 impl Drop for WatchedOutput {
813 if self.is_owned && !<*mut nativeWatchedOutput>::is_null(self.inner) {
814 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
818 /// Frees any resources used by the WatchedOutput, if is_owned is set and inner is non-NULL.
820 pub extern "C" fn WatchedOutput_free(this_obj: WatchedOutput) { }
822 /// Used only if an object of this type is returned as a trait impl by a method
823 pub(crate) extern "C" fn WatchedOutput_free_void(this_ptr: *mut c_void) {
824 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeWatchedOutput); }
828 pub(crate) fn get_native_ref(&self) -> &'static nativeWatchedOutput {
829 unsafe { &*ObjOps::untweak_ptr(self.inner) }
831 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeWatchedOutput {
832 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
834 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
835 pub(crate) fn take_inner(mut self) -> *mut nativeWatchedOutput {
836 assert!(self.is_owned);
837 let ret = ObjOps::untweak_ptr(self.inner);
838 self.inner = core::ptr::null_mut();
842 /// First block where the transaction output may have been spent.
844 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
846 pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crate::c_types::ThirtyTwoBytes {
847 let mut inner_val = &mut this_ptr.get_native_mut_ref().block_hash;
848 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() } } };
851 /// First block where the transaction output may have been spent.
853 /// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
855 pub extern "C" fn WatchedOutput_set_block_hash(this_ptr: &mut WatchedOutput, mut val: crate::c_types::ThirtyTwoBytes) {
856 let mut local_val = if val.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap() }) };
857 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.block_hash = local_val;
859 /// Outpoint identifying the transaction output.
861 pub extern "C" fn WatchedOutput_get_outpoint(this_ptr: &WatchedOutput) -> crate::lightning::chain::transaction::OutPoint {
862 let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint;
863 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 }
865 /// Outpoint identifying the transaction output.
867 pub extern "C" fn WatchedOutput_set_outpoint(this_ptr: &mut WatchedOutput, mut val: crate::lightning::chain::transaction::OutPoint) {
868 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
870 /// Spending condition of the transaction output.
872 pub extern "C" fn WatchedOutput_get_script_pubkey(this_ptr: &WatchedOutput) -> crate::c_types::u8slice {
873 let mut inner_val = &mut this_ptr.get_native_mut_ref().script_pubkey;
874 crate::c_types::u8slice::from_slice(&inner_val[..])
876 /// Spending condition of the transaction output.
878 pub extern "C" fn WatchedOutput_set_script_pubkey(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::CVec_u8Z) {
879 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.script_pubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust());
881 /// Constructs a new WatchedOutput given each field
884 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 {
885 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() }) };
886 WatchedOutput { inner: ObjOps::heap_alloc(nativeWatchedOutput {
887 block_hash: local_block_hash_arg,
888 outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
889 script_pubkey: ::bitcoin::blockdata::script::Script::from(script_pubkey_arg.into_rust()),
892 impl Clone for WatchedOutput {
893 fn clone(&self) -> Self {
895 inner: if <*mut nativeWatchedOutput>::is_null(self.inner) { core::ptr::null_mut() } else {
896 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
902 /// Used only if an object of this type is returned as a trait impl by a method
903 pub(crate) extern "C" fn WatchedOutput_clone_void(this_ptr: *const c_void) -> *mut c_void {
904 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeWatchedOutput)).clone() })) as *mut c_void
907 /// Creates a copy of the WatchedOutput
908 pub extern "C" fn WatchedOutput_clone(orig: &WatchedOutput) -> WatchedOutput {
911 /// Checks if two WatchedOutputs contain equal inner contents.
913 pub extern "C" fn WatchedOutput_hash(o: &WatchedOutput) -> u64 {
914 if o.inner.is_null() { return 0; }
915 // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
917 let mut hasher = core::hash::SipHasher::new();
918 core::hash::Hash::hash(o.get_native_ref(), &mut hasher);
919 core::hash::Hasher::finish(&hasher)