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 std::str::FromStr;
13 use core::convert::Infallible;
14 use bitcoin::hashes::Hash;
15 use crate::c_types::*;
17 pub mod chaininterface;
19 pub mod channelmonitor;
21 pub mod keysinterface;
24 use std::str::FromStr;
26 use core::convert::Infallible;
27 use bitcoin::hashes::Hash;
28 use crate::c_types::*;
33 use std::str::FromStr;
35 use core::convert::Infallible;
36 use bitcoin::hashes::Hash;
37 use crate::c_types::*;
41 use lightning::chain::BestBlock as nativeBestBlockImport;
42 pub(crate) type nativeBestBlock = nativeBestBlockImport;
44 /// The best known block as identified by its hash and height.
47 pub struct BestBlock {
48 /// A pointer to the opaque Rust object.
50 /// Nearly everywhere, inner must be non-null, however in places where
51 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
52 pub inner: *mut nativeBestBlock,
53 /// Indicates that this is the only struct which contains the same pointer.
55 /// Rust functions which take ownership of an object provided via an argument require
56 /// this to be true and invalidate the object pointed to by inner.
60 impl Drop for BestBlock {
62 if self.is_owned && !<*mut nativeBestBlock>::is_null(self.inner) {
63 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
67 /// Frees any resources used by the BestBlock, if is_owned is set and inner is non-NULL.
69 pub extern "C" fn BestBlock_free(this_obj: BestBlock) { }
71 /// Used only if an object of this type is returned as a trait impl by a method
72 pub(crate) extern "C" fn BestBlock_free_void(this_ptr: *mut c_void) {
73 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeBestBlock); }
77 pub(crate) fn get_native_ref(&self) -> &'static nativeBestBlock {
78 unsafe { &*ObjOps::untweak_ptr(self.inner) }
80 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBestBlock {
81 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
83 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
84 pub(crate) fn take_inner(mut self) -> *mut nativeBestBlock {
85 assert!(self.is_owned);
86 let ret = ObjOps::untweak_ptr(self.inner);
87 self.inner = std::ptr::null_mut();
91 impl Clone for BestBlock {
92 fn clone(&self) -> Self {
94 inner: if <*mut nativeBestBlock>::is_null(self.inner) { std::ptr::null_mut() } else {
95 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
101 /// Used only if an object of this type is returned as a trait impl by a method
102 pub(crate) extern "C" fn BestBlock_clone_void(this_ptr: *const c_void) -> *mut c_void {
103 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeBestBlock)).clone() })) as *mut c_void
106 /// Creates a copy of the BestBlock
107 pub extern "C" fn BestBlock_clone(orig: &BestBlock) -> BestBlock {
110 /// Constructs a `BestBlock` that represents the genesis block at height 0 of the given
114 pub extern "C" fn BestBlock_from_genesis(mut network: crate::bitcoin::network::Network) -> BestBlock {
115 let mut ret = lightning::chain::BestBlock::from_genesis(network.into_bitcoin());
116 BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
119 /// Returns a `BestBlock` as identified by the given block hash and height.
122 pub extern "C" fn BestBlock_new(mut block_hash: crate::c_types::ThirtyTwoBytes, mut height: u32) -> BestBlock {
123 let mut ret = lightning::chain::BestBlock::new(::bitcoin::hash_types::BlockHash::from_slice(&block_hash.data[..]).unwrap(), height);
124 BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
127 /// Returns the best block hash.
130 pub extern "C" fn BestBlock_block_hash(this_arg: &BestBlock) -> crate::c_types::ThirtyTwoBytes {
131 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_hash();
132 crate::c_types::ThirtyTwoBytes { data: ret.into_inner() }
135 /// Returns the best block height.
138 pub extern "C" fn BestBlock_height(this_arg: &BestBlock) -> u32 {
139 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.height();
143 /// An error when accessing the chain via [`Access`].
147 pub enum AccessError {
148 /// The requested chain is unknown.
150 /// The requested transaction doesn't exist or hasn't confirmed.
153 use lightning::chain::AccessError as nativeAccessError;
156 pub(crate) fn to_native(&self) -> nativeAccessError {
158 AccessError::UnknownChain => nativeAccessError::UnknownChain,
159 AccessError::UnknownTx => nativeAccessError::UnknownTx,
163 pub(crate) fn into_native(self) -> nativeAccessError {
165 AccessError::UnknownChain => nativeAccessError::UnknownChain,
166 AccessError::UnknownTx => nativeAccessError::UnknownTx,
170 pub(crate) fn from_native(native: &nativeAccessError) -> Self {
172 nativeAccessError::UnknownChain => AccessError::UnknownChain,
173 nativeAccessError::UnknownTx => AccessError::UnknownTx,
177 pub(crate) fn native_into(native: nativeAccessError) -> Self {
179 nativeAccessError::UnknownChain => AccessError::UnknownChain,
180 nativeAccessError::UnknownTx => AccessError::UnknownTx,
184 /// Creates a copy of the AccessError
186 pub extern "C" fn AccessError_clone(orig: &AccessError) -> AccessError {
190 /// Utility method to constructs a new UnknownChain-variant AccessError
191 pub extern "C" fn AccessError_unknown_chain() -> AccessError {
192 AccessError::UnknownChain}
194 /// Utility method to constructs a new UnknownTx-variant AccessError
195 pub extern "C" fn AccessError_unknown_tx() -> AccessError {
196 AccessError::UnknownTx}
197 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
201 /// An opaque pointer which is passed to your function implementations as an argument.
202 /// This has no meaning in the LDK, and can be NULL or any other value.
203 pub this_arg: *mut c_void,
204 /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
205 /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
208 /// [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
210 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,
211 /// Frees any resources associated with this object given its this_arg pointer.
212 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
213 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
215 unsafe impl Send for Access {}
216 unsafe impl Sync for Access {}
218 pub(crate) extern "C" fn Access_clone_fields(orig: &Access) -> Access {
220 this_arg: orig.this_arg,
221 get_utxo: Clone::clone(&orig.get_utxo),
222 free: Clone::clone(&orig.free),
226 use lightning::chain::Access as rustAccess;
227 impl rustAccess for Access {
228 fn get_utxo(&self, mut genesis_hash: &bitcoin::hash_types::BlockHash, mut short_channel_id: u64) -> Result<bitcoin::blockdata::transaction::TxOut, lightning::chain::AccessError> {
229 let mut ret = (self.get_utxo)(self.this_arg, genesis_hash.as_inner(), short_channel_id);
230 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() })};
235 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
236 // directly as a Deref trait in higher-level structs:
237 impl std::ops::Deref for Access {
239 fn deref(&self) -> &Self {
243 /// Calls the free function if one is set
245 pub extern "C" fn Access_free(this_ptr: Access) { }
246 impl Drop for Access {
248 if let Some(f) = self.free {
253 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
256 /// Useful when needing to replay chain data upon startup or as new chain events occur. Clients
257 /// sourcing chain data using a block-oriented API should prefer this interface over [`Confirm`].
258 /// Such clients fetch the entire header chain whereas clients using [`Confirm`] only fetch headers
262 /// An opaque pointer which is passed to your function implementations as an argument.
263 /// This has no meaning in the LDK, and can be NULL or any other value.
264 pub this_arg: *mut c_void,
265 /// Notifies the listener that a block was added at the given height.
266 pub block_connected: extern "C" fn (this_arg: *const c_void, block: crate::c_types::u8slice, height: u32),
267 /// Notifies the listener that a block was removed at the given height.
268 pub block_disconnected: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
269 /// Frees any resources associated with this object given its this_arg pointer.
270 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
271 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
273 unsafe impl Send for Listen {}
274 unsafe impl Sync for Listen {}
276 pub(crate) extern "C" fn Listen_clone_fields(orig: &Listen) -> Listen {
278 this_arg: orig.this_arg,
279 block_connected: Clone::clone(&orig.block_connected),
280 block_disconnected: Clone::clone(&orig.block_disconnected),
281 free: Clone::clone(&orig.free),
285 use lightning::chain::Listen as rustListen;
286 impl rustListen for Listen {
287 fn block_connected(&self, mut block: &bitcoin::blockdata::block::Block, mut height: u32) {
288 let mut local_block = ::bitcoin::consensus::encode::serialize(block);
289 (self.block_connected)(self.this_arg, crate::c_types::u8slice::from_slice(&local_block), height)
291 fn block_disconnected(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
292 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
293 (self.block_disconnected)(self.this_arg, &local_header, height)
297 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
298 // directly as a Deref trait in higher-level structs:
299 impl std::ops::Deref for Listen {
301 fn deref(&self) -> &Self {
305 /// Calls the free function if one is set
307 pub extern "C" fn Listen_free(this_ptr: Listen) { }
308 impl Drop for Listen {
310 if let Some(f) = self.free {
315 /// The `Confirm` trait is used to notify when transactions have been confirmed on chain or
316 /// unconfirmed during a chain reorganization.
318 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
319 /// [`Listen`]. For instance, an Electrum client may implement [`Filter`] by subscribing to activity
320 /// related to registered transactions and outputs. Upon notification, it would pass along the
321 /// matching transactions using this interface.
325 /// The intended use is as follows:
326 /// - Call [`transactions_confirmed`] to process any on-chain activity of interest.
327 /// - Call [`transaction_unconfirmed`] to process any transaction returned by [`get_relevant_txids`]
328 /// that has been reorganized out of the chain.
329 /// - Call [`best_block_updated`] whenever a new chain tip becomes available.
333 /// Clients must call these methods in chain order. Specifically:
334 /// - Transactions confirmed in a block must be given before transactions confirmed in a later
336 /// - Dependent transactions within the same block must be given in topological order, possibly in
338 /// - Unconfirmed transactions must be given after the original confirmations and before any
341 /// See individual method documentation for further details.
343 /// [`transactions_confirmed`]: Self::transactions_confirmed
344 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
345 /// [`best_block_updated`]: Self::best_block_updated
346 /// [`get_relevant_txids`]: Self::get_relevant_txids
349 /// An opaque pointer which is passed to your function implementations as an argument.
350 /// This has no meaning in the LDK, and can be NULL or any other value.
351 pub this_arg: *mut c_void,
352 /// Processes transactions confirmed in a block with a given header and height.
354 /// Should be called for any transactions registered by [`Filter::register_tx`] or any
355 /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
356 /// appearing in the same block do not need to be included in the same call; instead, multiple
357 /// calls with additional transactions may be made so long as they are made in [chain order].
359 /// May be called before or after [`best_block_updated`] for the corresponding block. However,
360 /// in the event of a chain reorganization, it must not be called with a `header` that is no
361 /// longer in the chain as of the last call to [`best_block_updated`].
363 /// [chain order]: Confirm#Order
364 /// [`best_block_updated`]: Self::best_block_updated
365 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),
366 /// Processes a transaction that is no longer confirmed as result of a chain reorganization.
368 /// Should be called for any transaction returned by [`get_relevant_txids`] if it has been
369 /// reorganized out of the best chain. Once called, the given transaction should not be returned
370 /// by [`get_relevant_txids`] unless it has been reconfirmed via [`transactions_confirmed`].
372 /// [`get_relevant_txids`]: Self::get_relevant_txids
373 /// [`transactions_confirmed`]: Self::transactions_confirmed
374 pub transaction_unconfirmed: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32]),
375 /// Processes an update to the best header connected at the given height.
377 /// Should be called when a new header is available but may be skipped for intermediary blocks
378 /// if they become available at the same time.
379 pub best_block_updated: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
380 /// Returns transactions that should be monitored for reorganization out of the chain.
382 /// Should include any transactions passed to [`transactions_confirmed`] that have insufficient
383 /// confirmations to be safe from a chain reorganization. Should not include any transactions
384 /// passed to [`transaction_unconfirmed`] unless later reconfirmed.
386 /// May be called to determine the subset of transactions that must still be monitored for
387 /// reorganization. Will be idempotent between calls but may change as a result of calls to the
388 /// other interface methods. Thus, this is useful to determine which transactions may need to be
389 /// given to [`transaction_unconfirmed`].
391 /// [`transactions_confirmed`]: Self::transactions_confirmed
392 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
394 pub get_relevant_txids: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_TxidZ,
395 /// Frees any resources associated with this object given its this_arg pointer.
396 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
397 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
399 unsafe impl Send for Confirm {}
400 unsafe impl Sync for Confirm {}
402 pub(crate) extern "C" fn Confirm_clone_fields(orig: &Confirm) -> Confirm {
404 this_arg: orig.this_arg,
405 transactions_confirmed: Clone::clone(&orig.transactions_confirmed),
406 transaction_unconfirmed: Clone::clone(&orig.transaction_unconfirmed),
407 best_block_updated: Clone::clone(&orig.best_block_updated),
408 get_relevant_txids: Clone::clone(&orig.get_relevant_txids),
409 free: Clone::clone(&orig.free),
413 use lightning::chain::Confirm as rustConfirm;
414 impl rustConfirm for Confirm {
415 fn transactions_confirmed(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
416 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
417 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 }); };
418 (self.transactions_confirmed)(self.this_arg, &local_header, local_txdata.into(), height)
420 fn transaction_unconfirmed(&self, mut txid: &bitcoin::hash_types::Txid) {
421 (self.transaction_unconfirmed)(self.this_arg, txid.as_inner())
423 fn best_block_updated(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
424 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
425 (self.best_block_updated)(self.this_arg, &local_header, height)
427 fn get_relevant_txids(&self) -> Vec<bitcoin::hash_types::Txid> {
428 let mut ret = (self.get_relevant_txids)(self.this_arg);
429 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() }); };
434 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
435 // directly as a Deref trait in higher-level structs:
436 impl std::ops::Deref for Confirm {
438 fn deref(&self) -> &Self {
442 /// Calls the free function if one is set
444 pub extern "C" fn Confirm_free(this_ptr: Confirm) { }
445 impl Drop for Confirm {
447 if let Some(f) = self.free {
452 /// An error enum representing a failure to persist a channel monitor update.
456 pub enum ChannelMonitorUpdateErr {
457 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
458 /// our state failed, but is expected to succeed at some point in the future).
460 /// Such a failure will \"freeze\" a channel, preventing us from revoking old states or
461 /// submitting new commitment transactions to the counterparty. Once the update(s) that failed
462 /// have been successfully applied, a [`MonitorEvent::UpdateCompleted`] event should be returned
463 /// via [`Watch::release_pending_monitor_events`] which will then restore the channel to an
464 /// operational state.
466 /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
467 /// you return a TemporaryFailure you must ensure that it is written to disk safely before
468 /// writing out the latest ChannelManager state.
470 /// Even when a channel has been \"frozen\" updates to the ChannelMonitor can continue to occur
471 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
472 /// to claim it on this channel) and those updates must be applied wherever they can be. At
473 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
474 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
475 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
478 /// Note that even if updates made after TemporaryFailure succeed you must still provide a
479 /// [`MonitorEvent::UpdateCompleted`] to ensure you have the latest monitor and re-enable
480 /// normal channel operation. Note that this is normally generated through a call to
481 /// [`ChainMonitor::channel_monitor_updated`].
483 /// Note that the update being processed here will not be replayed for you when you return a
484 /// [`MonitorEvent::UpdateCompleted`] event via [`Watch::release_pending_monitor_events`], so
485 /// you must store the update itself on your own local disk prior to returning a
486 /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
487 /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
490 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
491 /// remote location (with local copies persisted immediately), it is anticipated that all
492 /// updates will return TemporaryFailure until the remote copies could be updated.
494 /// [`ChainMonitor::channel_monitor_updated`]: chainmonitor::ChainMonitor::channel_monitor_updated
496 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
497 /// different watchtower and cannot update with all watchtowers that were previously informed
498 /// of this channel).
500 /// At reception of this error, ChannelManager will force-close the channel and return at
501 /// least a final ChannelMonitorUpdate::ChannelForceClosed which must be delivered to at
502 /// least one ChannelMonitor copy. Revocation secret MUST NOT be released and offchain channel
503 /// update must be rejected.
505 /// This failure may also signal a failure to update the local persisted copy of one of
506 /// the channel monitor instance.
508 /// Note that even when you fail a holder commitment transaction update, you must store the
509 /// update to ensure you can claim from it in case of a duplicate copy of this ChannelMonitor
510 /// broadcasts it (e.g distributed channel-monitor deployment)
512 /// In case of distributed watchtowers deployment, the new version must be written to disk, as
513 /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
514 /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
515 /// lagging behind on block processing.
518 use lightning::chain::ChannelMonitorUpdateErr as nativeChannelMonitorUpdateErr;
519 impl ChannelMonitorUpdateErr {
521 pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateErr {
523 ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
524 ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
528 pub(crate) fn into_native(self) -> nativeChannelMonitorUpdateErr {
530 ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
531 ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
535 pub(crate) fn from_native(native: &nativeChannelMonitorUpdateErr) -> Self {
537 nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
538 nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
542 pub(crate) fn native_into(native: nativeChannelMonitorUpdateErr) -> Self {
544 nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
545 nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
549 /// Creates a copy of the ChannelMonitorUpdateErr
551 pub extern "C" fn ChannelMonitorUpdateErr_clone(orig: &ChannelMonitorUpdateErr) -> ChannelMonitorUpdateErr {
555 /// Utility method to constructs a new TemporaryFailure-variant ChannelMonitorUpdateErr
556 pub extern "C" fn ChannelMonitorUpdateErr_temporary_failure() -> ChannelMonitorUpdateErr {
557 ChannelMonitorUpdateErr::TemporaryFailure}
559 /// Utility method to constructs a new PermanentFailure-variant ChannelMonitorUpdateErr
560 pub extern "C" fn ChannelMonitorUpdateErr_permanent_failure() -> ChannelMonitorUpdateErr {
561 ChannelMonitorUpdateErr::PermanentFailure}
562 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
563 /// blocks are connected and disconnected.
565 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
566 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
567 /// channel state changes and HTLCs are resolved. See method documentation for specific
570 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
571 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
572 /// without taking any further action such as persisting the current state.
574 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
575 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
576 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
577 /// funds in the channel. See [`ChannelMonitorUpdateErr`] for more details about how to handle
578 /// multiple instances.
580 /// [`PermanentFailure`]: ChannelMonitorUpdateErr::PermanentFailure
583 /// An opaque pointer which is passed to your function implementations as an argument.
584 /// This has no meaning in the LDK, and can be NULL or any other value.
585 pub this_arg: *mut c_void,
586 /// Watches a channel identified by `funding_txo` using `monitor`.
588 /// Implementations are responsible for watching the chain for the funding transaction along
589 /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
590 /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
592 /// Note: this interface MUST error with `ChannelMonitorUpdateErr::PermanentFailure` if
593 /// the given `funding_txo` has previously been registered via `watch_channel`.
595 /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
596 /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
597 /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
599 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,
600 /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
602 /// Implementations must call [`update_monitor`] with the given update. See
603 /// [`ChannelMonitorUpdateErr`] for invariants around returning an error.
605 /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
607 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,
608 /// Returns any monitor events since the last call. Subsequent calls must only return new
611 /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
612 /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
615 /// For details on asynchronous [`ChannelMonitor`] updating and returning
616 /// [`MonitorEvent::UpdateCompleted`] here, see [`ChannelMonitorUpdateErr::TemporaryFailure`].
618 pub release_pending_monitor_events: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_MonitorEventZ,
619 /// Frees any resources associated with this object given its this_arg pointer.
620 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
621 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
623 unsafe impl Send for Watch {}
624 unsafe impl Sync for Watch {}
626 pub(crate) extern "C" fn Watch_clone_fields(orig: &Watch) -> Watch {
628 this_arg: orig.this_arg,
629 watch_channel: Clone::clone(&orig.watch_channel),
630 update_channel: Clone::clone(&orig.update_channel),
631 release_pending_monitor_events: Clone::clone(&orig.release_pending_monitor_events),
632 free: Clone::clone(&orig.free),
636 use lightning::chain::Watch as rustWatch;
637 impl rustWatch<crate::lightning::chain::keysinterface::Sign> for Watch {
638 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> {
639 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 });
640 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() })};
643 fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: lightning::chain::channelmonitor::ChannelMonitorUpdate) -> Result<(), lightning::chain::ChannelMonitorUpdateErr> {
644 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 });
645 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() })};
648 fn release_pending_monitor_events(&self) -> Vec<lightning::chain::channelmonitor::MonitorEvent> {
649 let mut ret = (self.release_pending_monitor_events)(self.this_arg);
650 let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { item.into_native() }); };
655 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
656 // directly as a Deref trait in higher-level structs:
657 impl std::ops::Deref for Watch {
659 fn deref(&self) -> &Self {
663 /// Calls the free function if one is set
665 pub extern "C" fn Watch_free(this_ptr: Watch) { }
666 impl Drop for Watch {
668 if let Some(f) = self.free {
673 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
676 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
677 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
678 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
679 /// receiving full blocks from a chain source, any further filtering is unnecessary.
681 /// After an output has been registered, subsequent block retrievals from the chain source must not
682 /// exclude any transactions matching the new criteria nor any in-block descendants of such
685 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
686 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
687 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
688 /// invocation that has called the `Filter` must return [`TemporaryFailure`].
690 /// [`TemporaryFailure`]: ChannelMonitorUpdateErr::TemporaryFailure
691 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
692 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
695 /// An opaque pointer which is passed to your function implementations as an argument.
696 /// This has no meaning in the LDK, and can be NULL or any other value.
697 pub this_arg: *mut c_void,
698 /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
699 /// a spending condition.
700 pub register_tx: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32], script_pubkey: crate::c_types::u8slice),
701 /// Registers interest in spends of a transaction output.
703 /// Optionally, when `output.block_hash` is set, should return any transaction spending the
704 /// output that is found in the corresponding block along with its index.
706 /// This return value is useful for Electrum clients in order to supply in-block descendant
707 /// transactions which otherwise were not included. This is not necessary for other clients if
708 /// such descendant transactions were already included (e.g., when a BIP 157 client provides the
711 pub register_output: extern "C" fn (this_arg: *const c_void, output: crate::lightning::chain::WatchedOutput) -> crate::c_types::derived::COption_C2Tuple_usizeTransactionZZ,
712 /// Frees any resources associated with this object given its this_arg pointer.
713 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
714 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
716 unsafe impl Send for Filter {}
717 unsafe impl Sync for Filter {}
719 pub(crate) extern "C" fn Filter_clone_fields(orig: &Filter) -> Filter {
721 this_arg: orig.this_arg,
722 register_tx: Clone::clone(&orig.register_tx),
723 register_output: Clone::clone(&orig.register_output),
724 free: Clone::clone(&orig.free),
728 use lightning::chain::Filter as rustFilter;
729 impl rustFilter for Filter {
730 fn register_tx(&self, mut txid: &bitcoin::hash_types::Txid, mut script_pubkey: &bitcoin::blockdata::script::Script) {
731 (self.register_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pubkey[..]))
733 fn register_output(&self, mut output: lightning::chain::WatchedOutput) -> Option<(usize, bitcoin::blockdata::transaction::Transaction)> {
734 let mut ret = (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: ObjOps::heap_alloc(output), is_owned: true });
735 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 };
740 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
741 // directly as a Deref trait in higher-level structs:
742 impl std::ops::Deref for Filter {
744 fn deref(&self) -> &Self {
748 /// Calls the free function if one is set
750 pub extern "C" fn Filter_free(this_ptr: Filter) { }
751 impl Drop for Filter {
753 if let Some(f) = self.free {
759 use lightning::chain::WatchedOutput as nativeWatchedOutputImport;
760 pub(crate) type nativeWatchedOutput = nativeWatchedOutputImport;
762 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
764 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
765 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
766 /// the return value of [`Filter::register_output`].
768 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
769 /// may have been spent there. See [`Filter::register_output`] for details.
771 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
772 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
775 pub struct WatchedOutput {
776 /// A pointer to the opaque Rust object.
778 /// Nearly everywhere, inner must be non-null, however in places where
779 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
780 pub inner: *mut nativeWatchedOutput,
781 /// Indicates that this is the only struct which contains the same pointer.
783 /// Rust functions which take ownership of an object provided via an argument require
784 /// this to be true and invalidate the object pointed to by inner.
788 impl Drop for WatchedOutput {
790 if self.is_owned && !<*mut nativeWatchedOutput>::is_null(self.inner) {
791 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
795 /// Frees any resources used by the WatchedOutput, if is_owned is set and inner is non-NULL.
797 pub extern "C" fn WatchedOutput_free(this_obj: WatchedOutput) { }
799 /// Used only if an object of this type is returned as a trait impl by a method
800 pub(crate) extern "C" fn WatchedOutput_free_void(this_ptr: *mut c_void) {
801 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeWatchedOutput); }
805 pub(crate) fn get_native_ref(&self) -> &'static nativeWatchedOutput {
806 unsafe { &*ObjOps::untweak_ptr(self.inner) }
808 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeWatchedOutput {
809 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
811 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
812 pub(crate) fn take_inner(mut self) -> *mut nativeWatchedOutput {
813 assert!(self.is_owned);
814 let ret = ObjOps::untweak_ptr(self.inner);
815 self.inner = std::ptr::null_mut();
819 /// First block where the transaction output may have been spent.
821 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
823 pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crate::c_types::ThirtyTwoBytes {
824 let mut inner_val = &mut this_ptr.get_native_mut_ref().block_hash;
825 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() } } };
828 /// First block where the transaction output may have been spent.
830 /// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
832 pub extern "C" fn WatchedOutput_set_block_hash(this_ptr: &mut WatchedOutput, mut val: crate::c_types::ThirtyTwoBytes) {
833 let mut local_val = if val.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap() }) };
834 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.block_hash = local_val;
836 /// Outpoint identifying the transaction output.
838 pub extern "C" fn WatchedOutput_get_outpoint(this_ptr: &WatchedOutput) -> crate::lightning::chain::transaction::OutPoint {
839 let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint;
840 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 }
842 /// Outpoint identifying the transaction output.
844 pub extern "C" fn WatchedOutput_set_outpoint(this_ptr: &mut WatchedOutput, mut val: crate::lightning::chain::transaction::OutPoint) {
845 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
847 /// Spending condition of the transaction output.
849 pub extern "C" fn WatchedOutput_get_script_pubkey(this_ptr: &WatchedOutput) -> crate::c_types::u8slice {
850 let mut inner_val = &mut this_ptr.get_native_mut_ref().script_pubkey;
851 crate::c_types::u8slice::from_slice(&inner_val[..])
853 /// Spending condition of the transaction output.
855 pub extern "C" fn WatchedOutput_set_script_pubkey(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::CVec_u8Z) {
856 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.script_pubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust());
858 /// Constructs a new WatchedOutput given each field
861 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 {
862 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() }) };
863 WatchedOutput { inner: ObjOps::heap_alloc(nativeWatchedOutput {
864 block_hash: local_block_hash_arg,
865 outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
866 script_pubkey: ::bitcoin::blockdata::script::Script::from(script_pubkey_arg.into_rust()),
869 impl Clone for WatchedOutput {
870 fn clone(&self) -> Self {
872 inner: if <*mut nativeWatchedOutput>::is_null(self.inner) { std::ptr::null_mut() } else {
873 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
879 /// Used only if an object of this type is returned as a trait impl by a method
880 pub(crate) extern "C" fn WatchedOutput_clone_void(this_ptr: *const c_void) -> *mut c_void {
881 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeWatchedOutput)).clone() })) as *mut c_void
884 /// Creates a copy of the WatchedOutput
885 pub extern "C" fn WatchedOutput_clone(orig: &WatchedOutput) -> WatchedOutput {
888 /// Checks if two WatchedOutputs contain equal inner contents.
890 pub extern "C" fn WatchedOutput_hash(o: &WatchedOutput) -> u64 {
891 if o.inner.is_null() { return 0; }
892 // Note that we'd love to use std::collections::hash_map::DefaultHasher but it's not in core
894 let mut hasher = core::hash::SipHasher::new();
895 std::hash::Hash::hash(o.get_native_ref(), &mut hasher);
896 std::hash::Hasher::finish(&hasher)