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 /// Checks if two BestBlocks contain equal inner contents.
117 /// This ignores pointers and is_owned flags and looks at the values in fields.
118 /// Two objects with NULL inner values will be considered "equal" here.
120 pub extern "C" fn BestBlock_eq(a: &BestBlock, b: &BestBlock) -> bool {
121 if a.inner == b.inner { return true; }
122 if a.inner.is_null() || b.inner.is_null() { return false; }
123 if a.get_native_ref() == b.get_native_ref() { true } else { false }
125 /// Constructs a `BestBlock` that represents the genesis block at height 0 of the given
129 pub extern "C" fn BestBlock_from_genesis(mut network: crate::bitcoin::network::Network) -> crate::lightning::chain::BestBlock {
130 let mut ret = lightning::chain::BestBlock::from_genesis(network.into_bitcoin());
131 crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
134 /// Returns a `BestBlock` as identified by the given block hash and height.
137 pub extern "C" fn BestBlock_new(mut block_hash: crate::c_types::ThirtyTwoBytes, mut height: u32) -> crate::lightning::chain::BestBlock {
138 let mut ret = lightning::chain::BestBlock::new(::bitcoin::hash_types::BlockHash::from_slice(&block_hash.data[..]).unwrap(), height);
139 crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
142 /// Returns the best block hash.
145 pub extern "C" fn BestBlock_block_hash(this_arg: &crate::lightning::chain::BestBlock) -> crate::c_types::ThirtyTwoBytes {
146 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_hash();
147 crate::c_types::ThirtyTwoBytes { data: ret.into_inner() }
150 /// Returns the best block height.
153 pub extern "C" fn BestBlock_height(this_arg: &crate::lightning::chain::BestBlock) -> u32 {
154 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.height();
158 /// An error when accessing the chain via [`Access`].
162 pub enum AccessError {
163 /// The requested chain is unknown.
165 /// The requested transaction doesn't exist or hasn't confirmed.
168 use lightning::chain::AccessError as AccessErrorImport;
169 pub(crate) type nativeAccessError = AccessErrorImport;
173 pub(crate) fn to_native(&self) -> nativeAccessError {
175 AccessError::UnknownChain => nativeAccessError::UnknownChain,
176 AccessError::UnknownTx => nativeAccessError::UnknownTx,
180 pub(crate) fn into_native(self) -> nativeAccessError {
182 AccessError::UnknownChain => nativeAccessError::UnknownChain,
183 AccessError::UnknownTx => nativeAccessError::UnknownTx,
187 pub(crate) fn from_native(native: &nativeAccessError) -> Self {
189 nativeAccessError::UnknownChain => AccessError::UnknownChain,
190 nativeAccessError::UnknownTx => AccessError::UnknownTx,
194 pub(crate) fn native_into(native: nativeAccessError) -> Self {
196 nativeAccessError::UnknownChain => AccessError::UnknownChain,
197 nativeAccessError::UnknownTx => AccessError::UnknownTx,
201 /// Creates a copy of the AccessError
203 pub extern "C" fn AccessError_clone(orig: &AccessError) -> AccessError {
207 /// Utility method to constructs a new UnknownChain-variant AccessError
208 pub extern "C" fn AccessError_unknown_chain() -> AccessError {
209 AccessError::UnknownChain}
211 /// Utility method to constructs a new UnknownTx-variant AccessError
212 pub extern "C" fn AccessError_unknown_tx() -> AccessError {
213 AccessError::UnknownTx}
214 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
218 /// An opaque pointer which is passed to your function implementations as an argument.
219 /// This has no meaning in the LDK, and can be NULL or any other value.
220 pub this_arg: *mut c_void,
221 /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
222 /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
225 /// [`short_channel_id`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#definition-of-short_channel_id
227 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,
228 /// Frees any resources associated with this object given its this_arg pointer.
229 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
230 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
232 unsafe impl Send for Access {}
233 unsafe impl Sync for Access {}
235 pub(crate) extern "C" fn Access_clone_fields(orig: &Access) -> Access {
237 this_arg: orig.this_arg,
238 get_utxo: Clone::clone(&orig.get_utxo),
239 free: Clone::clone(&orig.free),
243 use lightning::chain::Access as rustAccess;
244 impl rustAccess for Access {
245 fn get_utxo(&self, mut genesis_hash: &bitcoin::hash_types::BlockHash, mut short_channel_id: u64) -> Result<bitcoin::blockdata::transaction::TxOut, lightning::chain::AccessError> {
246 let mut ret = (self.get_utxo)(self.this_arg, genesis_hash.as_inner(), short_channel_id);
247 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() })};
252 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
253 // directly as a Deref trait in higher-level structs:
254 impl core::ops::Deref for Access {
256 fn deref(&self) -> &Self {
260 /// Calls the free function if one is set
262 pub extern "C" fn Access_free(this_ptr: Access) { }
263 impl Drop for Access {
265 if let Some(f) = self.free {
270 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
273 /// Useful when needing to replay chain data upon startup or as new chain events occur. Clients
274 /// sourcing chain data using a block-oriented API should prefer this interface over [`Confirm`].
275 /// Such clients fetch the entire header chain whereas clients using [`Confirm`] only fetch headers
278 /// By using [`Listen::filtered_block_connected`] this interface supports clients fetching the
279 /// entire header chain and only blocks with matching transaction data using BIP 157 filters or
280 /// other similar filtering.
283 /// An opaque pointer which is passed to your function implementations as an argument.
284 /// This has no meaning in the LDK, and can be NULL or any other value.
285 pub this_arg: *mut c_void,
286 /// Notifies the listener that a block was added at the given height, with the transaction data
287 /// possibly filtered.
288 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),
289 /// Notifies the listener that a block was added at the given height.
290 pub block_connected: extern "C" fn (this_arg: *const c_void, block: crate::c_types::u8slice, height: u32),
291 /// Notifies the listener that a block was removed at the given height.
292 pub block_disconnected: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
293 /// Frees any resources associated with this object given its this_arg pointer.
294 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
295 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
297 unsafe impl Send for Listen {}
298 unsafe impl Sync for Listen {}
300 pub(crate) extern "C" fn Listen_clone_fields(orig: &Listen) -> Listen {
302 this_arg: orig.this_arg,
303 filtered_block_connected: Clone::clone(&orig.filtered_block_connected),
304 block_connected: Clone::clone(&orig.block_connected),
305 block_disconnected: Clone::clone(&orig.block_disconnected),
306 free: Clone::clone(&orig.free),
310 use lightning::chain::Listen as rustListen;
311 impl rustListen for Listen {
312 fn filtered_block_connected(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
313 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
314 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 }); };
315 (self.filtered_block_connected)(self.this_arg, &local_header, local_txdata.into(), height)
317 fn block_connected(&self, mut block: &bitcoin::blockdata::block::Block, mut height: u32) {
318 let mut local_block = ::bitcoin::consensus::encode::serialize(block);
319 (self.block_connected)(self.this_arg, crate::c_types::u8slice::from_slice(&local_block), height)
321 fn block_disconnected(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
322 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
323 (self.block_disconnected)(self.this_arg, &local_header, height)
327 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
328 // directly as a Deref trait in higher-level structs:
329 impl core::ops::Deref for Listen {
331 fn deref(&self) -> &Self {
335 /// Calls the free function if one is set
337 pub extern "C" fn Listen_free(this_ptr: Listen) { }
338 impl Drop for Listen {
340 if let Some(f) = self.free {
345 /// The `Confirm` trait is used to notify when transactions have been confirmed on chain or
346 /// unconfirmed during a chain reorganization.
348 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
349 /// [`Listen`]. For instance, an Electrum client may implement [`Filter`] by subscribing to activity
350 /// related to registered transactions and outputs. Upon notification, it would pass along the
351 /// matching transactions using this interface.
355 /// The intended use is as follows:
356 /// - Call [`transactions_confirmed`] to process any on-chain activity of interest.
357 /// - Call [`transaction_unconfirmed`] to process any transaction returned by [`get_relevant_txids`]
358 /// that has been reorganized out of the chain.
359 /// - Call [`best_block_updated`] whenever a new chain tip becomes available.
363 /// Clients must call these methods in chain order. Specifically:
364 /// - Transactions confirmed in a block must be given before transactions confirmed in a later
366 /// - Dependent transactions within the same block must be given in topological order, possibly in
368 /// - Unconfirmed transactions must be given after the original confirmations and before any
371 /// See individual method documentation for further details.
373 /// [`transactions_confirmed`]: Self::transactions_confirmed
374 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
375 /// [`best_block_updated`]: Self::best_block_updated
376 /// [`get_relevant_txids`]: Self::get_relevant_txids
379 /// An opaque pointer which is passed to your function implementations as an argument.
380 /// This has no meaning in the LDK, and can be NULL or any other value.
381 pub this_arg: *mut c_void,
382 /// Processes transactions confirmed in a block with a given header and height.
384 /// Should be called for any transactions registered by [`Filter::register_tx`] or any
385 /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
386 /// appearing in the same block do not need to be included in the same call; instead, multiple
387 /// calls with additional transactions may be made so long as they are made in [chain order].
389 /// May be called before or after [`best_block_updated`] for the corresponding block. However,
390 /// in the event of a chain reorganization, it must not be called with a `header` that is no
391 /// longer in the chain as of the last call to [`best_block_updated`].
393 /// [chain order]: Confirm#order
394 /// [`best_block_updated`]: Self::best_block_updated
395 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),
396 /// Processes a transaction that is no longer confirmed as result of a chain reorganization.
398 /// Should be called for any transaction returned by [`get_relevant_txids`] if it has been
399 /// reorganized out of the best chain. Once called, the given transaction will not be returned
400 /// by [`get_relevant_txids`], unless it has been reconfirmed via [`transactions_confirmed`].
402 /// [`get_relevant_txids`]: Self::get_relevant_txids
403 /// [`transactions_confirmed`]: Self::transactions_confirmed
404 pub transaction_unconfirmed: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32]),
405 /// Processes an update to the best header connected at the given height.
407 /// Should be called when a new header is available but may be skipped for intermediary blocks
408 /// if they become available at the same time.
409 pub best_block_updated: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
410 /// Returns transactions that should be monitored for reorganization out of the chain.
412 /// Will include any transactions passed to [`transactions_confirmed`] that have insufficient
413 /// confirmations to be safe from a chain reorganization. Will not include any transactions
414 /// passed to [`transaction_unconfirmed`], unless later reconfirmed.
416 /// May be called to determine the subset of transactions that must still be monitored for
417 /// reorganization. Will be idempotent between calls but may change as a result of calls to the
418 /// other interface methods. Thus, this is useful to determine which transactions may need to be
419 /// given to [`transaction_unconfirmed`].
421 /// [`transactions_confirmed`]: Self::transactions_confirmed
422 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
424 pub get_relevant_txids: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_TxidZ,
425 /// Frees any resources associated with this object given its this_arg pointer.
426 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
427 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
429 unsafe impl Send for Confirm {}
430 unsafe impl Sync for Confirm {}
432 pub(crate) extern "C" fn Confirm_clone_fields(orig: &Confirm) -> Confirm {
434 this_arg: orig.this_arg,
435 transactions_confirmed: Clone::clone(&orig.transactions_confirmed),
436 transaction_unconfirmed: Clone::clone(&orig.transaction_unconfirmed),
437 best_block_updated: Clone::clone(&orig.best_block_updated),
438 get_relevant_txids: Clone::clone(&orig.get_relevant_txids),
439 free: Clone::clone(&orig.free),
443 use lightning::chain::Confirm as rustConfirm;
444 impl rustConfirm for Confirm {
445 fn transactions_confirmed(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
446 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
447 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 }); };
448 (self.transactions_confirmed)(self.this_arg, &local_header, local_txdata.into(), height)
450 fn transaction_unconfirmed(&self, mut txid: &bitcoin::hash_types::Txid) {
451 (self.transaction_unconfirmed)(self.this_arg, txid.as_inner())
453 fn best_block_updated(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
454 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
455 (self.best_block_updated)(self.this_arg, &local_header, height)
457 fn get_relevant_txids(&self) -> Vec<bitcoin::hash_types::Txid> {
458 let mut ret = (self.get_relevant_txids)(self.this_arg);
459 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() }); };
464 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
465 // directly as a Deref trait in higher-level structs:
466 impl core::ops::Deref for Confirm {
468 fn deref(&self) -> &Self {
472 /// Calls the free function if one is set
474 pub extern "C" fn Confirm_free(this_ptr: Confirm) { }
475 impl Drop for Confirm {
477 if let Some(f) = self.free {
482 /// An enum representing the status of a channel monitor update persistence.
486 pub enum ChannelMonitorUpdateStatus {
487 /// The update has been durably persisted and all copies of the relevant [`ChannelMonitor`]
488 /// have been updated.
490 /// This includes performing any `fsync()` calls required to ensure the update is guaranteed to
491 /// be available on restart even if the application crashes.
493 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
494 /// our state failed, but is expected to succeed at some point in the future).
496 /// Such a failure will \"freeze\" a channel, preventing us from revoking old states or
497 /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
498 /// have been successfully applied, a [`MonitorEvent::Completed`] can be used to restore the
499 /// channel to an operational state.
501 /// Note that a given [`ChannelManager`] will *never* re-generate a [`ChannelMonitorUpdate`].
502 /// If you return this error you must ensure that it is written to disk safely before writing
503 /// the latest [`ChannelManager`] state, or you should return [`PermanentFailure`] instead.
505 /// Even when a channel has been \"frozen\", updates to the [`ChannelMonitor`] can continue to
506 /// occur (e.g. if an inbound HTLC which we forwarded was claimed upstream, resulting in us
507 /// attempting to claim it on this channel) and those updates must still be persisted.
509 /// No updates to the channel will be made which could invalidate other [`ChannelMonitor`]s
510 /// until a [`MonitorEvent::Completed`] is provided, even if you return no error on a later
511 /// monitor update for the same channel.
513 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
514 /// remote location (with local copies persisted immediately), it is anticipated that all
515 /// updates will return [`InProgress`] until the remote copies could be updated.
517 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
518 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
519 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
521 /// Used to indicate no further channel monitor updates will be allowed (likely a disk failure
522 /// or a remote copy of this [`ChannelMonitor`] is no longer reachable and thus not updatable).
524 /// When this is returned, [`ChannelManager`] will force-close the channel but *not* broadcast
525 /// our current commitment transaction. This avoids a dangerous case where a local disk failure
526 /// (e.g. the Linux-default remounting of the disk as read-only) causes [`PermanentFailure`]s
527 /// for all monitor updates. If we were to broadcast our latest commitment transaction and then
528 /// restart, we could end up reading a previous [`ChannelMonitor`] and [`ChannelManager`],
529 /// revoking our now-broadcasted state before seeing it confirm and losing all our funds.
531 /// Note that this is somewhat of a tradeoff - if the disk is really gone and we may have lost
532 /// the data permanently, we really should broadcast immediately. If the data can be recovered
533 /// with manual intervention, we'd rather close the channel, rejecting future updates to it,
534 /// and broadcast the latest state only if we have HTLCs to claim which are timing out (which
535 /// we do as long as blocks are connected).
537 /// In order to broadcast the latest local commitment transaction, you'll need to call
538 /// [`ChannelMonitor::get_latest_holder_commitment_txn`] and broadcast the resulting
539 /// transactions once you've safely ensured no further channel updates can be generated by your
540 /// [`ChannelManager`].
542 /// Note that at least one final [`ChannelMonitorUpdate`] may still be provided, which must
543 /// still be processed by a running [`ChannelMonitor`]. This final update will mark the
544 /// [`ChannelMonitor`] as finalized, ensuring no further updates (e.g. revocation of the latest
545 /// commitment transaction) are allowed.
547 /// Note that even if you return a [`PermanentFailure`] due to unavailability of secondary
548 /// [`ChannelMonitor`] copies, you should still make an attempt to store the update where
549 /// possible to ensure you can claim HTLC outputs on the latest commitment transaction
550 /// broadcasted later.
552 /// In case of distributed watchtowers deployment, the new version must be written to disk, as
553 /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
554 /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
555 /// lagging behind on block processing.
557 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
558 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
561 use lightning::chain::ChannelMonitorUpdateStatus as ChannelMonitorUpdateStatusImport;
562 pub(crate) type nativeChannelMonitorUpdateStatus = ChannelMonitorUpdateStatusImport;
564 impl ChannelMonitorUpdateStatus {
566 pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateStatus {
568 ChannelMonitorUpdateStatus::Completed => nativeChannelMonitorUpdateStatus::Completed,
569 ChannelMonitorUpdateStatus::InProgress => nativeChannelMonitorUpdateStatus::InProgress,
570 ChannelMonitorUpdateStatus::PermanentFailure => nativeChannelMonitorUpdateStatus::PermanentFailure,
574 pub(crate) fn into_native(self) -> nativeChannelMonitorUpdateStatus {
576 ChannelMonitorUpdateStatus::Completed => nativeChannelMonitorUpdateStatus::Completed,
577 ChannelMonitorUpdateStatus::InProgress => nativeChannelMonitorUpdateStatus::InProgress,
578 ChannelMonitorUpdateStatus::PermanentFailure => nativeChannelMonitorUpdateStatus::PermanentFailure,
582 pub(crate) fn from_native(native: &nativeChannelMonitorUpdateStatus) -> Self {
584 nativeChannelMonitorUpdateStatus::Completed => ChannelMonitorUpdateStatus::Completed,
585 nativeChannelMonitorUpdateStatus::InProgress => ChannelMonitorUpdateStatus::InProgress,
586 nativeChannelMonitorUpdateStatus::PermanentFailure => ChannelMonitorUpdateStatus::PermanentFailure,
590 pub(crate) fn native_into(native: nativeChannelMonitorUpdateStatus) -> Self {
592 nativeChannelMonitorUpdateStatus::Completed => ChannelMonitorUpdateStatus::Completed,
593 nativeChannelMonitorUpdateStatus::InProgress => ChannelMonitorUpdateStatus::InProgress,
594 nativeChannelMonitorUpdateStatus::PermanentFailure => ChannelMonitorUpdateStatus::PermanentFailure,
598 /// Creates a copy of the ChannelMonitorUpdateStatus
600 pub extern "C" fn ChannelMonitorUpdateStatus_clone(orig: &ChannelMonitorUpdateStatus) -> ChannelMonitorUpdateStatus {
604 /// Utility method to constructs a new Completed-variant ChannelMonitorUpdateStatus
605 pub extern "C" fn ChannelMonitorUpdateStatus_completed() -> ChannelMonitorUpdateStatus {
606 ChannelMonitorUpdateStatus::Completed}
608 /// Utility method to constructs a new InProgress-variant ChannelMonitorUpdateStatus
609 pub extern "C" fn ChannelMonitorUpdateStatus_in_progress() -> ChannelMonitorUpdateStatus {
610 ChannelMonitorUpdateStatus::InProgress}
612 /// Utility method to constructs a new PermanentFailure-variant ChannelMonitorUpdateStatus
613 pub extern "C" fn ChannelMonitorUpdateStatus_permanent_failure() -> ChannelMonitorUpdateStatus {
614 ChannelMonitorUpdateStatus::PermanentFailure}
615 /// Checks if two ChannelMonitorUpdateStatuss contain equal inner contents.
616 /// This ignores pointers and is_owned flags and looks at the values in fields.
618 pub extern "C" fn ChannelMonitorUpdateStatus_eq(a: &ChannelMonitorUpdateStatus, b: &ChannelMonitorUpdateStatus) -> bool {
619 if &a.to_native() == &b.to_native() { true } else { false }
621 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
622 /// blocks are connected and disconnected.
624 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
625 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
626 /// channel state changes and HTLCs are resolved. See method documentation for specific
629 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
630 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
631 /// without taking any further action such as persisting the current state.
633 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
634 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
635 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
636 /// funds in the channel. See [`ChannelMonitorUpdateStatus`] for more details about how to handle
637 /// multiple instances.
639 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
642 /// An opaque pointer which is passed to your function implementations as an argument.
643 /// This has no meaning in the LDK, and can be NULL or any other value.
644 pub this_arg: *mut c_void,
645 /// Watches a channel identified by `funding_txo` using `monitor`.
647 /// Implementations are responsible for watching the chain for the funding transaction along
648 /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
649 /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
651 /// Note: this interface MUST error with [`ChannelMonitorUpdateStatus::PermanentFailure`] if
652 /// the given `funding_txo` has previously been registered via `watch_channel`.
654 /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
655 /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
656 /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
658 pub watch_channel: extern "C" fn (this_arg: *const c_void, funding_txo: crate::lightning::chain::transaction::OutPoint, monitor: crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::lightning::chain::ChannelMonitorUpdateStatus,
659 /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
661 /// Implementations must call [`update_monitor`] with the given update. See
662 /// [`ChannelMonitorUpdateStatus`] for invariants around returning an error.
664 /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
666 pub update_channel: extern "C" fn (this_arg: *const c_void, funding_txo: crate::lightning::chain::transaction::OutPoint, update: crate::lightning::chain::channelmonitor::ChannelMonitorUpdate) -> crate::lightning::chain::ChannelMonitorUpdateStatus,
667 /// Returns any monitor events since the last call. Subsequent calls must only return new
670 /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
671 /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
674 /// For details on asynchronous [`ChannelMonitor`] updating and returning
675 /// [`MonitorEvent::Completed`] here, see [`ChannelMonitorUpdateStatus::InProgress`].
677 pub release_pending_monitor_events: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C3Tuple_OutPointCVec_MonitorEventZPublicKeyZZ,
678 /// Frees any resources associated with this object given its this_arg pointer.
679 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
680 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
682 unsafe impl Send for Watch {}
683 unsafe impl Sync for Watch {}
685 pub(crate) extern "C" fn Watch_clone_fields(orig: &Watch) -> Watch {
687 this_arg: orig.this_arg,
688 watch_channel: Clone::clone(&orig.watch_channel),
689 update_channel: Clone::clone(&orig.update_channel),
690 release_pending_monitor_events: Clone::clone(&orig.release_pending_monitor_events),
691 free: Clone::clone(&orig.free),
695 use lightning::chain::Watch as rustWatch;
696 impl rustWatch<crate::lightning::chain::keysinterface::Sign> for Watch {
697 fn watch_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut monitor: lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::chain::keysinterface::Sign>) -> lightning::chain::ChannelMonitorUpdateStatus {
698 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 });
701 fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: lightning::chain::channelmonitor::ChannelMonitorUpdate) -> lightning::chain::ChannelMonitorUpdateStatus {
702 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 });
705 fn release_pending_monitor_events(&self) -> Vec<(lightning::chain::transaction::OutPoint, Vec<lightning::chain::channelmonitor::MonitorEvent>, Option<bitcoin::secp256k1::PublicKey>)> {
706 let mut ret = (self.release_pending_monitor_events)(self.this_arg);
707 let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = item.to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_native() }); }; let mut local_orig_ret_0_2 = if orig_ret_0_2.is_null() { None } else { Some( { orig_ret_0_2.into_rust() }) }; let mut local_ret_0 = (*unsafe { Box::from_raw(orig_ret_0_0.take_inner()) }, local_orig_ret_0_1, local_orig_ret_0_2); local_ret_0 }); };
712 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
713 // directly as a Deref trait in higher-level structs:
714 impl core::ops::Deref for Watch {
716 fn deref(&self) -> &Self {
720 /// Calls the free function if one is set
722 pub extern "C" fn Watch_free(this_ptr: Watch) { }
723 impl Drop for Watch {
725 if let Some(f) = self.free {
730 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
733 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
734 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
735 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
736 /// receiving full blocks from a chain source, any further filtering is unnecessary.
738 /// After an output has been registered, subsequent block retrievals from the chain source must not
739 /// exclude any transactions matching the new criteria nor any in-block descendants of such
742 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
743 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
744 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
745 /// invocation that has called the `Filter` must return [`InProgress`].
747 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
748 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
749 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
752 /// An opaque pointer which is passed to your function implementations as an argument.
753 /// This has no meaning in the LDK, and can be NULL or any other value.
754 pub this_arg: *mut c_void,
755 /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
756 /// a spending condition.
757 pub register_tx: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32], script_pubkey: crate::c_types::u8slice),
758 /// Registers interest in spends of a transaction output.
760 /// Note that this method might be called during processing of a new block. You therefore need
761 /// to ensure that also dependent output spents within an already connected block are correctly
762 /// handled, e.g., by re-scanning the block in question whenever new outputs have been
763 /// registered mid-processing.
764 pub register_output: extern "C" fn (this_arg: *const c_void, output: crate::lightning::chain::WatchedOutput),
765 /// Frees any resources associated with this object given its this_arg pointer.
766 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
767 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
769 unsafe impl Send for Filter {}
770 unsafe impl Sync for Filter {}
772 pub(crate) extern "C" fn Filter_clone_fields(orig: &Filter) -> Filter {
774 this_arg: orig.this_arg,
775 register_tx: Clone::clone(&orig.register_tx),
776 register_output: Clone::clone(&orig.register_output),
777 free: Clone::clone(&orig.free),
781 use lightning::chain::Filter as rustFilter;
782 impl rustFilter for Filter {
783 fn register_tx(&self, mut txid: &bitcoin::hash_types::Txid, mut script_pubkey: &bitcoin::blockdata::script::Script) {
784 (self.register_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pubkey[..]))
786 fn register_output(&self, mut output: lightning::chain::WatchedOutput) {
787 (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: ObjOps::heap_alloc(output), is_owned: true })
791 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
792 // directly as a Deref trait in higher-level structs:
793 impl core::ops::Deref for Filter {
795 fn deref(&self) -> &Self {
799 /// Calls the free function if one is set
801 pub extern "C" fn Filter_free(this_ptr: Filter) { }
802 impl Drop for Filter {
804 if let Some(f) = self.free {
810 use lightning::chain::WatchedOutput as nativeWatchedOutputImport;
811 pub(crate) type nativeWatchedOutput = nativeWatchedOutputImport;
813 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
815 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
816 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
817 /// [`Confirm::transactions_confirmed`].
819 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
820 /// may have been spent there. See [`Filter::register_output`] for details.
822 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
823 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
826 pub struct WatchedOutput {
827 /// A pointer to the opaque Rust object.
829 /// Nearly everywhere, inner must be non-null, however in places where
830 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
831 pub inner: *mut nativeWatchedOutput,
832 /// Indicates that this is the only struct which contains the same pointer.
834 /// Rust functions which take ownership of an object provided via an argument require
835 /// this to be true and invalidate the object pointed to by inner.
839 impl Drop for WatchedOutput {
841 if self.is_owned && !<*mut nativeWatchedOutput>::is_null(self.inner) {
842 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
846 /// Frees any resources used by the WatchedOutput, if is_owned is set and inner is non-NULL.
848 pub extern "C" fn WatchedOutput_free(this_obj: WatchedOutput) { }
850 /// Used only if an object of this type is returned as a trait impl by a method
851 pub(crate) extern "C" fn WatchedOutput_free_void(this_ptr: *mut c_void) {
852 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeWatchedOutput); }
856 pub(crate) fn get_native_ref(&self) -> &'static nativeWatchedOutput {
857 unsafe { &*ObjOps::untweak_ptr(self.inner) }
859 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeWatchedOutput {
860 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
862 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
863 pub(crate) fn take_inner(mut self) -> *mut nativeWatchedOutput {
864 assert!(self.is_owned);
865 let ret = ObjOps::untweak_ptr(self.inner);
866 self.inner = core::ptr::null_mut();
870 /// First block where the transaction output may have been spent.
872 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
874 pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crate::c_types::ThirtyTwoBytes {
875 let mut inner_val = &mut this_ptr.get_native_mut_ref().block_hash;
876 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() } } };
879 /// First block where the transaction output may have been spent.
881 /// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
883 pub extern "C" fn WatchedOutput_set_block_hash(this_ptr: &mut WatchedOutput, mut val: crate::c_types::ThirtyTwoBytes) {
884 let mut local_val = if val.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap() }) };
885 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.block_hash = local_val;
887 /// Outpoint identifying the transaction output.
889 pub extern "C" fn WatchedOutput_get_outpoint(this_ptr: &WatchedOutput) -> crate::lightning::chain::transaction::OutPoint {
890 let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint;
891 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 }
893 /// Outpoint identifying the transaction output.
895 pub extern "C" fn WatchedOutput_set_outpoint(this_ptr: &mut WatchedOutput, mut val: crate::lightning::chain::transaction::OutPoint) {
896 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
898 /// Spending condition of the transaction output.
900 pub extern "C" fn WatchedOutput_get_script_pubkey(this_ptr: &WatchedOutput) -> crate::c_types::u8slice {
901 let mut inner_val = &mut this_ptr.get_native_mut_ref().script_pubkey;
902 crate::c_types::u8slice::from_slice(&inner_val[..])
904 /// Spending condition of the transaction output.
906 pub extern "C" fn WatchedOutput_set_script_pubkey(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::CVec_u8Z) {
907 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.script_pubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust());
909 /// Constructs a new WatchedOutput given each field
912 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 {
913 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() }) };
914 WatchedOutput { inner: ObjOps::heap_alloc(nativeWatchedOutput {
915 block_hash: local_block_hash_arg,
916 outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
917 script_pubkey: ::bitcoin::blockdata::script::Script::from(script_pubkey_arg.into_rust()),
920 impl Clone for WatchedOutput {
921 fn clone(&self) -> Self {
923 inner: if <*mut nativeWatchedOutput>::is_null(self.inner) { core::ptr::null_mut() } else {
924 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
930 /// Used only if an object of this type is returned as a trait impl by a method
931 pub(crate) extern "C" fn WatchedOutput_clone_void(this_ptr: *const c_void) -> *mut c_void {
932 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeWatchedOutput)).clone() })) as *mut c_void
935 /// Creates a copy of the WatchedOutput
936 pub extern "C" fn WatchedOutput_clone(orig: &WatchedOutput) -> WatchedOutput {
939 /// Checks if two WatchedOutputs contain equal inner contents.
940 /// This ignores pointers and is_owned flags and looks at the values in fields.
941 /// Two objects with NULL inner values will be considered "equal" here.
943 pub extern "C" fn WatchedOutput_eq(a: &WatchedOutput, b: &WatchedOutput) -> bool {
944 if a.inner == b.inner { return true; }
945 if a.inner.is_null() || b.inner.is_null() { return false; }
946 if a.get_native_ref() == b.get_native_ref() { true } else { false }
948 /// Checks if two WatchedOutputs contain equal inner contents.
950 pub extern "C" fn WatchedOutput_hash(o: &WatchedOutput) -> u64 {
951 if o.inner.is_null() { return 0; }
952 // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
954 let mut hasher = core::hash::SipHasher::new();
955 core::hash::Hash::hash(o.get_native_ref(), &mut hasher);
956 core::hash::Hasher::finish(&hasher)