1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
4 // This file is licensed under the license available in the LICENSE or LICENSE.md
5 // file in the root of this repository or, if no such file exists, the same
6 // license as that which applies to the original source files from which this
7 // source was automatically generated.
9 //! Structs and traits which allow other parts of rust-lightning to interact with the blockchain.
11 use alloc::str::FromStr;
12 use core::ffi::c_void;
13 use core::convert::Infallible;
14 use bitcoin::hashes::Hash;
15 use crate::c_types::*;
16 #[cfg(feature="no-std")]
17 use alloc::{vec::Vec, boxed::Box};
19 pub mod chaininterface;
21 pub mod channelmonitor;
23 pub mod keysinterface;
26 use alloc::str::FromStr;
27 use core::ffi::c_void;
28 use core::convert::Infallible;
29 use bitcoin::hashes::Hash;
30 use crate::c_types::*;
31 #[cfg(feature="no-std")]
32 use alloc::{vec::Vec, boxed::Box};
37 use alloc::str::FromStr;
38 use core::ffi::c_void;
39 use core::convert::Infallible;
40 use bitcoin::hashes::Hash;
41 use crate::c_types::*;
42 #[cfg(feature="no-std")]
43 use alloc::{vec::Vec, boxed::Box};
47 use lightning::chain::BestBlock as nativeBestBlockImport;
48 pub(crate) type nativeBestBlock = nativeBestBlockImport;
50 /// The best known block as identified by its hash and height.
53 pub struct BestBlock {
54 /// A pointer to the opaque Rust object.
56 /// Nearly everywhere, inner must be non-null, however in places where
57 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
58 pub inner: *mut nativeBestBlock,
59 /// Indicates that this is the only struct which contains the same pointer.
61 /// Rust functions which take ownership of an object provided via an argument require
62 /// this to be true and invalidate the object pointed to by inner.
66 impl Drop for BestBlock {
68 if self.is_owned && !<*mut nativeBestBlock>::is_null(self.inner) {
69 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
73 /// Frees any resources used by the BestBlock, if is_owned is set and inner is non-NULL.
75 pub extern "C" fn BestBlock_free(this_obj: BestBlock) { }
77 /// Used only if an object of this type is returned as a trait impl by a method
78 pub(crate) extern "C" fn BestBlock_free_void(this_ptr: *mut c_void) {
79 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeBestBlock) };
83 pub(crate) fn get_native_ref(&self) -> &'static nativeBestBlock {
84 unsafe { &*ObjOps::untweak_ptr(self.inner) }
86 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBestBlock {
87 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
89 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
90 pub(crate) fn take_inner(mut self) -> *mut nativeBestBlock {
91 assert!(self.is_owned);
92 let ret = ObjOps::untweak_ptr(self.inner);
93 self.inner = core::ptr::null_mut();
97 impl Clone for BestBlock {
98 fn clone(&self) -> Self {
100 inner: if <*mut nativeBestBlock>::is_null(self.inner) { core::ptr::null_mut() } else {
101 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
107 /// Used only if an object of this type is returned as a trait impl by a method
108 pub(crate) extern "C" fn BestBlock_clone_void(this_ptr: *const c_void) -> *mut c_void {
109 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeBestBlock)).clone() })) as *mut c_void
112 /// Creates a copy of the BestBlock
113 pub extern "C" fn BestBlock_clone(orig: &BestBlock) -> BestBlock {
116 /// Checks if two BestBlocks contain equal inner contents.
117 /// This ignores pointers and is_owned flags and looks at the values in fields.
118 /// Two objects with NULL inner values will be considered "equal" here.
120 pub extern "C" fn BestBlock_eq(a: &BestBlock, b: &BestBlock) -> bool {
121 if a.inner == b.inner { return true; }
122 if a.inner.is_null() || b.inner.is_null() { return false; }
123 if a.get_native_ref() == b.get_native_ref() { true } else { false }
125 /// Constructs a `BestBlock` that represents the genesis block at height 0 of the given
129 pub extern "C" fn BestBlock_from_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 LDK when relevant transactions have been confirmed on
346 /// chain or 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-based transaction sync implementation may implement
350 /// [`Filter`] to subscribe to relevant transactions and unspent outputs it should monitor for
351 /// on-chain activity. Then, it needs to notify LDK via this interface upon observing any changes
352 /// with reference to the confirmation status of the monitored objects.
355 /// The intended use is as follows:
356 /// - Call [`transactions_confirmed`] to notify LDK whenever any of the registered transactions or
357 /// outputs are, respectively, confirmed or spent on chain.
358 /// - Call [`transaction_unconfirmed`] to notify LDK whenever any transaction returned by
359 /// [`get_relevant_txids`] is no longer confirmed in the block with the given block hash.
360 /// - Call [`best_block_updated`] to notify LDK whenever a new chain tip becomes available.
364 /// Clients must call these methods in chain order. Specifically:
365 /// - Transactions which are confirmed in a particular block must be given before transactions
366 /// confirmed in a later block.
367 /// - Dependent transactions within the same block must be given in topological order, possibly in
369 /// - All unconfirmed transactions must be given after the original confirmations and before *any*
370 /// reconfirmations, i.e., [`transactions_confirmed`] and [`transaction_unconfirmed`] calls should
371 /// never be interleaved, but always conduced *en bloc*.
372 /// - Any reconfirmed transactions need to be explicitly unconfirmed before they are reconfirmed
373 /// in regard to the new block.
375 /// See individual method documentation for further details.
377 /// [`transactions_confirmed`]: Self::transactions_confirmed
378 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
379 /// [`best_block_updated`]: Self::best_block_updated
380 /// [`get_relevant_txids`]: Self::get_relevant_txids
383 /// An opaque pointer which is passed to your function implementations as an argument.
384 /// This has no meaning in the LDK, and can be NULL or any other value.
385 pub this_arg: *mut c_void,
386 /// Notifies LDK of transactions confirmed in a block with a given header and height.
388 /// Must be called for any transactions registered by [`Filter::register_tx`] or any
389 /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
390 /// appearing in the same block do not need to be included in the same call; instead, multiple
391 /// calls with additional transactions may be made so long as they are made in [chain order].
393 /// May be called before or after [`best_block_updated`] for the corresponding block. However,
394 /// in the event of a chain reorganization, it must not be called with a `header` that is no
395 /// longer in the chain as of the last call to [`best_block_updated`].
397 /// [chain order]: Confirm#order
398 /// [`best_block_updated`]: Self::best_block_updated
399 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),
400 /// Notifies LDK of a transaction that is no longer confirmed as result of a chain reorganization.
402 /// Must be called for any transaction returned by [`get_relevant_txids`] if it has been
403 /// reorganized out of the best chain or if it is no longer confirmed in the block with the
404 /// given block hash. Once called, the given transaction will not be returned
405 /// by [`get_relevant_txids`], unless it has been reconfirmed via [`transactions_confirmed`].
407 /// [`get_relevant_txids`]: Self::get_relevant_txids
408 /// [`transactions_confirmed`]: Self::transactions_confirmed
409 pub transaction_unconfirmed: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32]),
410 /// Notifies LDK of an update to the best header connected at the given height.
412 /// Must be called whenever a new chain tip becomes available. May be skipped for intermediary
414 pub best_block_updated: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
415 /// Returns transactions that must be monitored for reorganization out of the chain along
416 /// with the hash of the block as part of which it had been previously confirmed.
418 /// Will include any transactions passed to [`transactions_confirmed`] that have insufficient
419 /// confirmations to be safe from a chain reorganization. Will not include any transactions
420 /// passed to [`transaction_unconfirmed`], unless later reconfirmed.
422 /// Must be called to determine the subset of transactions that must be monitored for
423 /// reorganization. Will be idempotent between calls but may change as a result of calls to the
424 /// other interface methods. Thus, this is useful to determine which transactions must be
425 /// given to [`transaction_unconfirmed`].
427 /// If any of the returned transactions are confirmed in a block other than the one with the
428 /// given hash, they need to be unconfirmed and reconfirmed via [`transaction_unconfirmed`] and
429 /// [`transactions_confirmed`], respectively.
431 /// [`transactions_confirmed`]: Self::transactions_confirmed
432 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
434 pub get_relevant_txids: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C2Tuple_TxidBlockHashZZ,
435 /// Frees any resources associated with this object given its this_arg pointer.
436 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
437 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
439 unsafe impl Send for Confirm {}
440 unsafe impl Sync for Confirm {}
442 pub(crate) extern "C" fn Confirm_clone_fields(orig: &Confirm) -> Confirm {
444 this_arg: orig.this_arg,
445 transactions_confirmed: Clone::clone(&orig.transactions_confirmed),
446 transaction_unconfirmed: Clone::clone(&orig.transaction_unconfirmed),
447 best_block_updated: Clone::clone(&orig.best_block_updated),
448 get_relevant_txids: Clone::clone(&orig.get_relevant_txids),
449 free: Clone::clone(&orig.free),
453 use lightning::chain::Confirm as rustConfirm;
454 impl rustConfirm for Confirm {
455 fn transactions_confirmed(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
456 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
457 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 }); };
458 (self.transactions_confirmed)(self.this_arg, &local_header, local_txdata.into(), height)
460 fn transaction_unconfirmed(&self, mut txid: &bitcoin::hash_types::Txid) {
461 (self.transaction_unconfirmed)(self.this_arg, txid.as_inner())
463 fn best_block_updated(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
464 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
465 (self.best_block_updated)(self.this_arg, &local_header, height)
467 fn get_relevant_txids(&self) -> Vec<(bitcoin::hash_types::Txid, Option<bitcoin::hash_types::BlockHash>)> {
468 let mut ret = (self.get_relevant_txids)(self.this_arg);
469 let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1) = item.to_rust(); let mut local_orig_ret_0_1 = if orig_ret_0_1.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&orig_ret_0_1.data[..]).unwrap() }) }; let mut local_ret_0 = (::bitcoin::hash_types::Txid::from_slice(&orig_ret_0_0.data[..]).unwrap(), local_orig_ret_0_1); local_ret_0 }); };
474 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
475 // directly as a Deref trait in higher-level structs:
476 impl core::ops::Deref for Confirm {
478 fn deref(&self) -> &Self {
482 /// Calls the free function if one is set
484 pub extern "C" fn Confirm_free(this_ptr: Confirm) { }
485 impl Drop for Confirm {
487 if let Some(f) = self.free {
492 /// An enum representing the status of a channel monitor update persistence.
496 pub enum ChannelMonitorUpdateStatus {
497 /// The update has been durably persisted and all copies of the relevant [`ChannelMonitor`]
498 /// have been updated.
500 /// This includes performing any `fsync()` calls required to ensure the update is guaranteed to
501 /// be available on restart even if the application crashes.
503 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
504 /// our state failed, but is expected to succeed at some point in the future).
506 /// Such a failure will \"freeze\" a channel, preventing us from revoking old states or
507 /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
508 /// have been successfully applied, a [`MonitorEvent::Completed`] can be used to restore the
509 /// channel to an operational state.
511 /// Note that a given [`ChannelManager`] will *never* re-generate a [`ChannelMonitorUpdate`].
512 /// If you return this error you must ensure that it is written to disk safely before writing
513 /// the latest [`ChannelManager`] state, or you should return [`PermanentFailure`] instead.
515 /// Even when a channel has been \"frozen\", updates to the [`ChannelMonitor`] can continue to
516 /// occur (e.g. if an inbound HTLC which we forwarded was claimed upstream, resulting in us
517 /// attempting to claim it on this channel) and those updates must still be persisted.
519 /// No updates to the channel will be made which could invalidate other [`ChannelMonitor`]s
520 /// until a [`MonitorEvent::Completed`] is provided, even if you return no error on a later
521 /// monitor update for the same channel.
523 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
524 /// remote location (with local copies persisted immediately), it is anticipated that all
525 /// updates will return [`InProgress`] until the remote copies could be updated.
527 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
528 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
529 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
531 /// Used to indicate no further channel monitor updates will be allowed (likely a disk failure
532 /// or a remote copy of this [`ChannelMonitor`] is no longer reachable and thus not updatable).
534 /// When this is returned, [`ChannelManager`] will force-close the channel but *not* broadcast
535 /// our current commitment transaction. This avoids a dangerous case where a local disk failure
536 /// (e.g. the Linux-default remounting of the disk as read-only) causes [`PermanentFailure`]s
537 /// for all monitor updates. If we were to broadcast our latest commitment transaction and then
538 /// restart, we could end up reading a previous [`ChannelMonitor`] and [`ChannelManager`],
539 /// revoking our now-broadcasted state before seeing it confirm and losing all our funds.
541 /// Note that this is somewhat of a tradeoff - if the disk is really gone and we may have lost
542 /// the data permanently, we really should broadcast immediately. If the data can be recovered
543 /// with manual intervention, we'd rather close the channel, rejecting future updates to it,
544 /// and broadcast the latest state only if we have HTLCs to claim which are timing out (which
545 /// we do as long as blocks are connected).
547 /// In order to broadcast the latest local commitment transaction, you'll need to call
548 /// [`ChannelMonitor::get_latest_holder_commitment_txn`] and broadcast the resulting
549 /// transactions once you've safely ensured no further channel updates can be generated by your
550 /// [`ChannelManager`].
552 /// Note that at least one final [`ChannelMonitorUpdate`] may still be provided, which must
553 /// still be processed by a running [`ChannelMonitor`]. This final update will mark the
554 /// [`ChannelMonitor`] as finalized, ensuring no further updates (e.g. revocation of the latest
555 /// commitment transaction) are allowed.
557 /// Note that even if you return a [`PermanentFailure`] due to unavailability of secondary
558 /// [`ChannelMonitor`] copies, you should still make an attempt to store the update where
559 /// possible to ensure you can claim HTLC outputs on the latest commitment transaction
560 /// broadcasted later.
562 /// In case of distributed watchtowers deployment, the new version must be written to disk, as
563 /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
564 /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
565 /// lagging behind on block processing.
567 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
568 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
571 use lightning::chain::ChannelMonitorUpdateStatus as ChannelMonitorUpdateStatusImport;
572 pub(crate) type nativeChannelMonitorUpdateStatus = ChannelMonitorUpdateStatusImport;
574 impl ChannelMonitorUpdateStatus {
576 pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateStatus {
578 ChannelMonitorUpdateStatus::Completed => nativeChannelMonitorUpdateStatus::Completed,
579 ChannelMonitorUpdateStatus::InProgress => nativeChannelMonitorUpdateStatus::InProgress,
580 ChannelMonitorUpdateStatus::PermanentFailure => nativeChannelMonitorUpdateStatus::PermanentFailure,
584 pub(crate) fn into_native(self) -> nativeChannelMonitorUpdateStatus {
586 ChannelMonitorUpdateStatus::Completed => nativeChannelMonitorUpdateStatus::Completed,
587 ChannelMonitorUpdateStatus::InProgress => nativeChannelMonitorUpdateStatus::InProgress,
588 ChannelMonitorUpdateStatus::PermanentFailure => nativeChannelMonitorUpdateStatus::PermanentFailure,
592 pub(crate) fn from_native(native: &nativeChannelMonitorUpdateStatus) -> Self {
594 nativeChannelMonitorUpdateStatus::Completed => ChannelMonitorUpdateStatus::Completed,
595 nativeChannelMonitorUpdateStatus::InProgress => ChannelMonitorUpdateStatus::InProgress,
596 nativeChannelMonitorUpdateStatus::PermanentFailure => ChannelMonitorUpdateStatus::PermanentFailure,
600 pub(crate) fn native_into(native: nativeChannelMonitorUpdateStatus) -> Self {
602 nativeChannelMonitorUpdateStatus::Completed => ChannelMonitorUpdateStatus::Completed,
603 nativeChannelMonitorUpdateStatus::InProgress => ChannelMonitorUpdateStatus::InProgress,
604 nativeChannelMonitorUpdateStatus::PermanentFailure => ChannelMonitorUpdateStatus::PermanentFailure,
608 /// Creates a copy of the ChannelMonitorUpdateStatus
610 pub extern "C" fn ChannelMonitorUpdateStatus_clone(orig: &ChannelMonitorUpdateStatus) -> ChannelMonitorUpdateStatus {
614 /// Utility method to constructs a new Completed-variant ChannelMonitorUpdateStatus
615 pub extern "C" fn ChannelMonitorUpdateStatus_completed() -> ChannelMonitorUpdateStatus {
616 ChannelMonitorUpdateStatus::Completed}
618 /// Utility method to constructs a new InProgress-variant ChannelMonitorUpdateStatus
619 pub extern "C" fn ChannelMonitorUpdateStatus_in_progress() -> ChannelMonitorUpdateStatus {
620 ChannelMonitorUpdateStatus::InProgress}
622 /// Utility method to constructs a new PermanentFailure-variant ChannelMonitorUpdateStatus
623 pub extern "C" fn ChannelMonitorUpdateStatus_permanent_failure() -> ChannelMonitorUpdateStatus {
624 ChannelMonitorUpdateStatus::PermanentFailure}
625 /// Checks if two ChannelMonitorUpdateStatuss contain equal inner contents.
626 /// This ignores pointers and is_owned flags and looks at the values in fields.
628 pub extern "C" fn ChannelMonitorUpdateStatus_eq(a: &ChannelMonitorUpdateStatus, b: &ChannelMonitorUpdateStatus) -> bool {
629 if &a.to_native() == &b.to_native() { true } else { false }
631 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
632 /// blocks are connected and disconnected.
634 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
635 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
636 /// channel state changes and HTLCs are resolved. See method documentation for specific
639 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
640 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
641 /// without taking any further action such as persisting the current state.
643 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
644 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
645 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
646 /// funds in the channel. See [`ChannelMonitorUpdateStatus`] for more details about how to handle
647 /// multiple instances.
649 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
652 /// An opaque pointer which is passed to your function implementations as an argument.
653 /// This has no meaning in the LDK, and can be NULL or any other value.
654 pub this_arg: *mut c_void,
655 /// Watches a channel identified by `funding_txo` using `monitor`.
657 /// Implementations are responsible for watching the chain for the funding transaction along
658 /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
659 /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
661 /// Note: this interface MUST error with [`ChannelMonitorUpdateStatus::PermanentFailure`] if
662 /// the given `funding_txo` has previously been registered via `watch_channel`.
664 /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
665 /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
666 /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
668 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,
669 /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
671 /// Implementations must call [`update_monitor`] with the given update. See
672 /// [`ChannelMonitorUpdateStatus`] for invariants around returning an error.
674 /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
676 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,
677 /// Returns any monitor events since the last call. Subsequent calls must only return new
680 /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
681 /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
684 /// For details on asynchronous [`ChannelMonitor`] updating and returning
685 /// [`MonitorEvent::Completed`] here, see [`ChannelMonitorUpdateStatus::InProgress`].
687 pub release_pending_monitor_events: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C3Tuple_OutPointCVec_MonitorEventZPublicKeyZZ,
688 /// Frees any resources associated with this object given its this_arg pointer.
689 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
690 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
692 unsafe impl Send for Watch {}
693 unsafe impl Sync for Watch {}
695 pub(crate) extern "C" fn Watch_clone_fields(orig: &Watch) -> Watch {
697 this_arg: orig.this_arg,
698 watch_channel: Clone::clone(&orig.watch_channel),
699 update_channel: Clone::clone(&orig.update_channel),
700 release_pending_monitor_events: Clone::clone(&orig.release_pending_monitor_events),
701 free: Clone::clone(&orig.free),
705 use lightning::chain::Watch as rustWatch;
706 impl rustWatch<crate::lightning::chain::keysinterface::Sign> for Watch {
707 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 {
708 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 });
711 fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: lightning::chain::channelmonitor::ChannelMonitorUpdate) -> lightning::chain::ChannelMonitorUpdateStatus {
712 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 });
715 fn release_pending_monitor_events(&self) -> Vec<(lightning::chain::transaction::OutPoint, Vec<lightning::chain::channelmonitor::MonitorEvent>, Option<bitcoin::secp256k1::PublicKey>)> {
716 let mut ret = (self.release_pending_monitor_events)(self.this_arg);
717 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 }); };
722 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
723 // directly as a Deref trait in higher-level structs:
724 impl core::ops::Deref for Watch {
726 fn deref(&self) -> &Self {
730 /// Calls the free function if one is set
732 pub extern "C" fn Watch_free(this_ptr: Watch) { }
733 impl Drop for Watch {
735 if let Some(f) = self.free {
740 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
743 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
744 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
745 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
746 /// receiving full blocks from a chain source, any further filtering is unnecessary.
748 /// After an output has been registered, subsequent block retrievals from the chain source must not
749 /// exclude any transactions matching the new criteria nor any in-block descendants of such
752 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
753 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
754 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
755 /// invocation that has called the `Filter` must return [`InProgress`].
757 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
758 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
759 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
762 /// An opaque pointer which is passed to your function implementations as an argument.
763 /// This has no meaning in the LDK, and can be NULL or any other value.
764 pub this_arg: *mut c_void,
765 /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
766 /// a spending condition.
767 pub register_tx: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32], script_pubkey: crate::c_types::u8slice),
768 /// Registers interest in spends of a transaction output.
770 /// Note that this method might be called during processing of a new block. You therefore need
771 /// to ensure that also dependent output spents within an already connected block are correctly
772 /// handled, e.g., by re-scanning the block in question whenever new outputs have been
773 /// registered mid-processing.
774 pub register_output: extern "C" fn (this_arg: *const c_void, output: crate::lightning::chain::WatchedOutput),
775 /// Frees any resources associated with this object given its this_arg pointer.
776 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
777 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
779 unsafe impl Send for Filter {}
780 unsafe impl Sync for Filter {}
782 pub(crate) extern "C" fn Filter_clone_fields(orig: &Filter) -> Filter {
784 this_arg: orig.this_arg,
785 register_tx: Clone::clone(&orig.register_tx),
786 register_output: Clone::clone(&orig.register_output),
787 free: Clone::clone(&orig.free),
791 use lightning::chain::Filter as rustFilter;
792 impl rustFilter for Filter {
793 fn register_tx(&self, mut txid: &bitcoin::hash_types::Txid, mut script_pubkey: &bitcoin::blockdata::script::Script) {
794 (self.register_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pubkey[..]))
796 fn register_output(&self, mut output: lightning::chain::WatchedOutput) {
797 (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: ObjOps::heap_alloc(output), is_owned: true })
801 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
802 // directly as a Deref trait in higher-level structs:
803 impl core::ops::Deref for Filter {
805 fn deref(&self) -> &Self {
809 /// Calls the free function if one is set
811 pub extern "C" fn Filter_free(this_ptr: Filter) { }
812 impl Drop for Filter {
814 if let Some(f) = self.free {
820 use lightning::chain::WatchedOutput as nativeWatchedOutputImport;
821 pub(crate) type nativeWatchedOutput = nativeWatchedOutputImport;
823 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
825 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
826 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
827 /// [`Confirm::transactions_confirmed`].
829 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
830 /// may have been spent there. See [`Filter::register_output`] for details.
832 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
833 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
836 pub struct WatchedOutput {
837 /// A pointer to the opaque Rust object.
839 /// Nearly everywhere, inner must be non-null, however in places where
840 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
841 pub inner: *mut nativeWatchedOutput,
842 /// Indicates that this is the only struct which contains the same pointer.
844 /// Rust functions which take ownership of an object provided via an argument require
845 /// this to be true and invalidate the object pointed to by inner.
849 impl Drop for WatchedOutput {
851 if self.is_owned && !<*mut nativeWatchedOutput>::is_null(self.inner) {
852 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
856 /// Frees any resources used by the WatchedOutput, if is_owned is set and inner is non-NULL.
858 pub extern "C" fn WatchedOutput_free(this_obj: WatchedOutput) { }
860 /// Used only if an object of this type is returned as a trait impl by a method
861 pub(crate) extern "C" fn WatchedOutput_free_void(this_ptr: *mut c_void) {
862 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeWatchedOutput) };
866 pub(crate) fn get_native_ref(&self) -> &'static nativeWatchedOutput {
867 unsafe { &*ObjOps::untweak_ptr(self.inner) }
869 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeWatchedOutput {
870 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
872 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
873 pub(crate) fn take_inner(mut self) -> *mut nativeWatchedOutput {
874 assert!(self.is_owned);
875 let ret = ObjOps::untweak_ptr(self.inner);
876 self.inner = core::ptr::null_mut();
880 /// First block where the transaction output may have been spent.
882 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
884 pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crate::c_types::ThirtyTwoBytes {
885 let mut inner_val = &mut this_ptr.get_native_mut_ref().block_hash;
886 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() } } };
889 /// First block where the transaction output may have been spent.
891 /// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
893 pub extern "C" fn WatchedOutput_set_block_hash(this_ptr: &mut WatchedOutput, mut val: crate::c_types::ThirtyTwoBytes) {
894 let mut local_val = if val.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap() }) };
895 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.block_hash = local_val;
897 /// Outpoint identifying the transaction output.
899 pub extern "C" fn WatchedOutput_get_outpoint(this_ptr: &WatchedOutput) -> crate::lightning::chain::transaction::OutPoint {
900 let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint;
901 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 }
903 /// Outpoint identifying the transaction output.
905 pub extern "C" fn WatchedOutput_set_outpoint(this_ptr: &mut WatchedOutput, mut val: crate::lightning::chain::transaction::OutPoint) {
906 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
908 /// Spending condition of the transaction output.
910 pub extern "C" fn WatchedOutput_get_script_pubkey(this_ptr: &WatchedOutput) -> crate::c_types::u8slice {
911 let mut inner_val = &mut this_ptr.get_native_mut_ref().script_pubkey;
912 crate::c_types::u8slice::from_slice(&inner_val[..])
914 /// Spending condition of the transaction output.
916 pub extern "C" fn WatchedOutput_set_script_pubkey(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::CVec_u8Z) {
917 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.script_pubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust());
919 /// Constructs a new WatchedOutput given each field
922 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 {
923 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() }) };
924 WatchedOutput { inner: ObjOps::heap_alloc(nativeWatchedOutput {
925 block_hash: local_block_hash_arg,
926 outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
927 script_pubkey: ::bitcoin::blockdata::script::Script::from(script_pubkey_arg.into_rust()),
930 impl Clone for WatchedOutput {
931 fn clone(&self) -> Self {
933 inner: if <*mut nativeWatchedOutput>::is_null(self.inner) { core::ptr::null_mut() } else {
934 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
940 /// Used only if an object of this type is returned as a trait impl by a method
941 pub(crate) extern "C" fn WatchedOutput_clone_void(this_ptr: *const c_void) -> *mut c_void {
942 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeWatchedOutput)).clone() })) as *mut c_void
945 /// Creates a copy of the WatchedOutput
946 pub extern "C" fn WatchedOutput_clone(orig: &WatchedOutput) -> WatchedOutput {
949 /// Checks if two WatchedOutputs contain equal inner contents.
950 /// This ignores pointers and is_owned flags and looks at the values in fields.
951 /// Two objects with NULL inner values will be considered "equal" here.
953 pub extern "C" fn WatchedOutput_eq(a: &WatchedOutput, b: &WatchedOutput) -> bool {
954 if a.inner == b.inner { return true; }
955 if a.inner.is_null() || b.inner.is_null() { return false; }
956 if a.get_native_ref() == b.get_native_ref() { true } else { false }
958 /// Checks if two WatchedOutputs contain equal inner contents.
960 pub extern "C" fn WatchedOutput_hash(o: &WatchedOutput) -> u64 {
961 if o.inner.is_null() { return 0; }
962 // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
964 let mut hasher = core::hash::SipHasher::new();
965 core::hash::Hash::hash(o.get_native_ref(), &mut hasher);
966 core::hash::Hasher::finish(&hasher)