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;
25 use alloc::str::FromStr;
26 use core::ffi::c_void;
27 use core::convert::Infallible;
28 use bitcoin::hashes::Hash;
29 use crate::c_types::*;
30 #[cfg(feature="no-std")]
31 use alloc::{vec::Vec, boxed::Box};
36 use alloc::str::FromStr;
37 use core::ffi::c_void;
38 use core::convert::Infallible;
39 use bitcoin::hashes::Hash;
40 use crate::c_types::*;
41 #[cfg(feature="no-std")]
42 use alloc::{vec::Vec, boxed::Box};
46 use lightning::chain::BestBlock as nativeBestBlockImport;
47 pub(crate) type nativeBestBlock = nativeBestBlockImport;
49 /// The best known block as identified by its hash and height.
52 pub struct BestBlock {
53 /// A pointer to the opaque Rust object.
55 /// Nearly everywhere, inner must be non-null, however in places where
56 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
57 pub inner: *mut nativeBestBlock,
58 /// Indicates that this is the only struct which contains the same pointer.
60 /// Rust functions which take ownership of an object provided via an argument require
61 /// this to be true and invalidate the object pointed to by inner.
65 impl Drop for BestBlock {
67 if self.is_owned && !<*mut nativeBestBlock>::is_null(self.inner) {
68 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
72 /// Frees any resources used by the BestBlock, if is_owned is set and inner is non-NULL.
74 pub extern "C" fn BestBlock_free(this_obj: BestBlock) { }
76 /// Used only if an object of this type is returned as a trait impl by a method
77 pub(crate) extern "C" fn BestBlock_free_void(this_ptr: *mut c_void) {
78 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeBestBlock) };
82 pub(crate) fn get_native_ref(&self) -> &'static nativeBestBlock {
83 unsafe { &*ObjOps::untweak_ptr(self.inner) }
85 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBestBlock {
86 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
88 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
89 pub(crate) fn take_inner(mut self) -> *mut nativeBestBlock {
90 assert!(self.is_owned);
91 let ret = ObjOps::untweak_ptr(self.inner);
92 self.inner = core::ptr::null_mut();
96 impl Clone for BestBlock {
97 fn clone(&self) -> Self {
99 inner: if <*mut nativeBestBlock>::is_null(self.inner) { core::ptr::null_mut() } else {
100 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
106 /// Used only if an object of this type is returned as a trait impl by a method
107 pub(crate) extern "C" fn BestBlock_clone_void(this_ptr: *const c_void) -> *mut c_void {
108 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeBestBlock)).clone() })) as *mut c_void
111 /// Creates a copy of the BestBlock
112 pub extern "C" fn BestBlock_clone(orig: &BestBlock) -> BestBlock {
115 /// Checks if two BestBlocks contain equal inner contents.
116 /// This ignores pointers and is_owned flags and looks at the values in fields.
117 /// Two objects with NULL inner values will be considered "equal" here.
119 pub extern "C" fn BestBlock_eq(a: &BestBlock, b: &BestBlock) -> bool {
120 if a.inner == b.inner { return true; }
121 if a.inner.is_null() || b.inner.is_null() { return false; }
122 if a.get_native_ref() == b.get_native_ref() { true } else { false }
124 /// Constructs a `BestBlock` that represents the genesis block at height 0 of the given
128 pub extern "C" fn BestBlock_from_network(mut network: crate::bitcoin::network::Network) -> crate::lightning::chain::BestBlock {
129 let mut ret = lightning::chain::BestBlock::from_network(network.into_bitcoin());
130 crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
133 /// Returns a `BestBlock` as identified by the given block hash and height.
136 pub extern "C" fn BestBlock_new(mut block_hash: crate::c_types::ThirtyTwoBytes, mut height: u32) -> crate::lightning::chain::BestBlock {
137 let mut ret = lightning::chain::BestBlock::new(::bitcoin::hash_types::BlockHash::from_slice(&block_hash.data[..]).unwrap(), height);
138 crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
141 /// Returns the best block hash.
144 pub extern "C" fn BestBlock_block_hash(this_arg: &crate::lightning::chain::BestBlock) -> crate::c_types::ThirtyTwoBytes {
145 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_hash();
146 crate::c_types::ThirtyTwoBytes { data: ret.into_inner() }
149 /// Returns the best block height.
152 pub extern "C" fn BestBlock_height(this_arg: &crate::lightning::chain::BestBlock) -> u32 {
153 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.height();
157 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
160 /// Useful when needing to replay chain data upon startup or as new chain events occur. Clients
161 /// sourcing chain data using a block-oriented API should prefer this interface over [`Confirm`].
162 /// Such clients fetch the entire header chain whereas clients using [`Confirm`] only fetch headers
165 /// By using [`Listen::filtered_block_connected`] this interface supports clients fetching the
166 /// entire header chain and only blocks with matching transaction data using BIP 157 filters or
167 /// other similar filtering.
170 /// An opaque pointer which is passed to your function implementations as an argument.
171 /// This has no meaning in the LDK, and can be NULL or any other value.
172 pub this_arg: *mut c_void,
173 /// Notifies the listener that a block was added at the given height, with the transaction data
174 /// possibly filtered.
175 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),
176 /// Notifies the listener that a block was added at the given height.
177 pub block_connected: extern "C" fn (this_arg: *const c_void, block: crate::c_types::u8slice, height: u32),
178 /// Notifies the listener that a block was removed at the given height.
179 pub block_disconnected: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
180 /// Frees any resources associated with this object given its this_arg pointer.
181 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
182 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
184 unsafe impl Send for Listen {}
185 unsafe impl Sync for Listen {}
187 pub(crate) extern "C" fn Listen_clone_fields(orig: &Listen) -> Listen {
189 this_arg: orig.this_arg,
190 filtered_block_connected: Clone::clone(&orig.filtered_block_connected),
191 block_connected: Clone::clone(&orig.block_connected),
192 block_disconnected: Clone::clone(&orig.block_disconnected),
193 free: Clone::clone(&orig.free),
197 use lightning::chain::Listen as rustListen;
198 impl rustListen for Listen {
199 fn filtered_block_connected(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
200 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
201 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 }); };
202 (self.filtered_block_connected)(self.this_arg, &local_header, local_txdata.into(), height)
204 fn block_connected(&self, mut block: &bitcoin::blockdata::block::Block, mut height: u32) {
205 let mut local_block = ::bitcoin::consensus::encode::serialize(block);
206 (self.block_connected)(self.this_arg, crate::c_types::u8slice::from_slice(&local_block), height)
208 fn block_disconnected(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
209 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
210 (self.block_disconnected)(self.this_arg, &local_header, height)
214 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
215 // directly as a Deref trait in higher-level structs:
216 impl core::ops::Deref for Listen {
218 fn deref(&self) -> &Self {
222 /// Calls the free function if one is set
224 pub extern "C" fn Listen_free(this_ptr: Listen) { }
225 impl Drop for Listen {
227 if let Some(f) = self.free {
232 /// The `Confirm` trait is used to notify LDK when relevant transactions have been confirmed on
233 /// chain or unconfirmed during a chain reorganization.
235 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
236 /// [`Listen`]. For instance, an Electrum-based transaction sync implementation may implement
237 /// [`Filter`] to subscribe to relevant transactions and unspent outputs it should monitor for
238 /// on-chain activity. Then, it needs to notify LDK via this interface upon observing any changes
239 /// with reference to the confirmation status of the monitored objects.
242 /// The intended use is as follows:
243 /// - Call [`transactions_confirmed`] to notify LDK whenever any of the registered transactions or
244 /// outputs are, respectively, confirmed or spent on chain.
245 /// - Call [`transaction_unconfirmed`] to notify LDK whenever any transaction returned by
246 /// [`get_relevant_txids`] is no longer confirmed in the block with the given block hash.
247 /// - Call [`best_block_updated`] to notify LDK whenever a new chain tip becomes available.
251 /// Clients must call these methods in chain order. Specifically:
252 /// - Transactions which are confirmed in a particular block must be given before transactions
253 /// confirmed in a later block.
254 /// - Dependent transactions within the same block must be given in topological order, possibly in
256 /// - All unconfirmed transactions must be given after the original confirmations and before *any*
257 /// reconfirmations, i.e., [`transactions_confirmed`] and [`transaction_unconfirmed`] calls should
258 /// never be interleaved, but always conduced *en bloc*.
259 /// - Any reconfirmed transactions need to be explicitly unconfirmed before they are reconfirmed
260 /// in regard to the new block.
262 /// See individual method documentation for further details.
264 /// [`transactions_confirmed`]: Self::transactions_confirmed
265 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
266 /// [`best_block_updated`]: Self::best_block_updated
267 /// [`get_relevant_txids`]: Self::get_relevant_txids
270 /// An opaque pointer which is passed to your function implementations as an argument.
271 /// This has no meaning in the LDK, and can be NULL or any other value.
272 pub this_arg: *mut c_void,
273 /// Notifies LDK of transactions confirmed in a block with a given header and height.
275 /// Must be called for any transactions registered by [`Filter::register_tx`] or any
276 /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
277 /// appearing in the same block do not need to be included in the same call; instead, multiple
278 /// calls with additional transactions may be made so long as they are made in [chain order].
280 /// May be called before or after [`best_block_updated`] for the corresponding block. However,
281 /// in the event of a chain reorganization, it must not be called with a `header` that is no
282 /// longer in the chain as of the last call to [`best_block_updated`].
284 /// [chain order]: Confirm#order
285 /// [`best_block_updated`]: Self::best_block_updated
286 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),
287 /// Notifies LDK of a transaction that is no longer confirmed as result of a chain reorganization.
289 /// Must be called for any transaction returned by [`get_relevant_txids`] if it has been
290 /// reorganized out of the best chain or if it is no longer confirmed in the block with the
291 /// given block hash. Once called, the given transaction will not be returned
292 /// by [`get_relevant_txids`], unless it has been reconfirmed via [`transactions_confirmed`].
294 /// [`get_relevant_txids`]: Self::get_relevant_txids
295 /// [`transactions_confirmed`]: Self::transactions_confirmed
296 pub transaction_unconfirmed: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32]),
297 /// Notifies LDK of an update to the best header connected at the given height.
299 /// Must be called whenever a new chain tip becomes available. May be skipped for intermediary
301 pub best_block_updated: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
302 /// Returns transactions that must be monitored for reorganization out of the chain along
303 /// with the hash of the block as part of which it had been previously confirmed.
305 /// Note that the returned `Option<BlockHash>` might be `None` for channels created with LDK
306 /// 0.0.112 and prior, in which case you need to manually track previous confirmations.
308 /// Will include any transactions passed to [`transactions_confirmed`] that have insufficient
309 /// confirmations to be safe from a chain reorganization. Will not include any transactions
310 /// passed to [`transaction_unconfirmed`], unless later reconfirmed.
312 /// Must be called to determine the subset of transactions that must be monitored for
313 /// reorganization. Will be idempotent between calls but may change as a result of calls to the
314 /// other interface methods. Thus, this is useful to determine which transactions must be
315 /// given to [`transaction_unconfirmed`].
317 /// If any of the returned transactions are confirmed in a block other than the one with the
318 /// given hash, they need to be unconfirmed and reconfirmed via [`transaction_unconfirmed`] and
319 /// [`transactions_confirmed`], respectively.
321 /// [`transactions_confirmed`]: Self::transactions_confirmed
322 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
323 pub get_relevant_txids: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C2Tuple_TxidCOption_BlockHashZZZ,
324 /// Frees any resources associated with this object given its this_arg pointer.
325 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
326 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
328 unsafe impl Send for Confirm {}
329 unsafe impl Sync for Confirm {}
331 pub(crate) extern "C" fn Confirm_clone_fields(orig: &Confirm) -> Confirm {
333 this_arg: orig.this_arg,
334 transactions_confirmed: Clone::clone(&orig.transactions_confirmed),
335 transaction_unconfirmed: Clone::clone(&orig.transaction_unconfirmed),
336 best_block_updated: Clone::clone(&orig.best_block_updated),
337 get_relevant_txids: Clone::clone(&orig.get_relevant_txids),
338 free: Clone::clone(&orig.free),
342 use lightning::chain::Confirm as rustConfirm;
343 impl rustConfirm for Confirm {
344 fn transactions_confirmed(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
345 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
346 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 }); };
347 (self.transactions_confirmed)(self.this_arg, &local_header, local_txdata.into(), height)
349 fn transaction_unconfirmed(&self, mut txid: &bitcoin::hash_types::Txid) {
350 (self.transaction_unconfirmed)(self.this_arg, txid.as_inner())
352 fn best_block_updated(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
353 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
354 (self.best_block_updated)(self.this_arg, &local_header, height)
356 fn get_relevant_txids(&self) -> Vec<(bitcoin::hash_types::Txid, Option<bitcoin::hash_types::BlockHash>)> {
357 let mut ret = (self.get_relevant_txids)(self.this_arg);
358 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 = { /*orig_ret_0_1*/ let orig_ret_0_1_opt = orig_ret_0_1; if orig_ret_0_1_opt.is_none() { None } else { Some({ { ::bitcoin::hash_types::BlockHash::from_slice(&{ orig_ret_0_1_opt.take() }.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 }); };
363 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
364 // directly as a Deref trait in higher-level structs:
365 impl core::ops::Deref for Confirm {
367 fn deref(&self) -> &Self {
371 /// Calls the free function if one is set
373 pub extern "C" fn Confirm_free(this_ptr: Confirm) { }
374 impl Drop for Confirm {
376 if let Some(f) = self.free {
381 /// An enum representing the status of a channel monitor update persistence.
385 pub enum ChannelMonitorUpdateStatus {
386 /// The update has been durably persisted and all copies of the relevant [`ChannelMonitor`]
387 /// have been updated.
389 /// This includes performing any `fsync()` calls required to ensure the update is guaranteed to
390 /// be available on restart even if the application crashes.
392 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
393 /// our state failed, but is expected to succeed at some point in the future).
395 /// Such a failure will \"freeze\" a channel, preventing us from revoking old states or
396 /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
397 /// have been successfully applied, a [`MonitorEvent::Completed`] can be used to restore the
398 /// channel to an operational state.
400 /// Note that a given [`ChannelManager`] will *never* re-generate a [`ChannelMonitorUpdate`].
401 /// If you return this error you must ensure that it is written to disk safely before writing
402 /// the latest [`ChannelManager`] state, or you should return [`PermanentFailure`] instead.
404 /// Even when a channel has been \"frozen\", updates to the [`ChannelMonitor`] can continue to
405 /// occur (e.g. if an inbound HTLC which we forwarded was claimed upstream, resulting in us
406 /// attempting to claim it on this channel) and those updates must still be persisted.
408 /// No updates to the channel will be made which could invalidate other [`ChannelMonitor`]s
409 /// until a [`MonitorEvent::Completed`] is provided, even if you return no error on a later
410 /// monitor update for the same channel.
412 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
413 /// remote location (with local copies persisted immediately), it is anticipated that all
414 /// updates will return [`InProgress`] until the remote copies could be updated.
416 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
417 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
418 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
420 /// Used to indicate no further channel monitor updates will be allowed (likely a disk failure
421 /// or a remote copy of this [`ChannelMonitor`] is no longer reachable and thus not updatable).
423 /// When this is returned, [`ChannelManager`] will force-close the channel but *not* broadcast
424 /// our current commitment transaction. This avoids a dangerous case where a local disk failure
425 /// (e.g. the Linux-default remounting of the disk as read-only) causes [`PermanentFailure`]s
426 /// for all monitor updates. If we were to broadcast our latest commitment transaction and then
427 /// restart, we could end up reading a previous [`ChannelMonitor`] and [`ChannelManager`],
428 /// revoking our now-broadcasted state before seeing it confirm and losing all our funds.
430 /// Note that this is somewhat of a tradeoff - if the disk is really gone and we may have lost
431 /// the data permanently, we really should broadcast immediately. If the data can be recovered
432 /// with manual intervention, we'd rather close the channel, rejecting future updates to it,
433 /// and broadcast the latest state only if we have HTLCs to claim which are timing out (which
434 /// we do as long as blocks are connected).
436 /// In order to broadcast the latest local commitment transaction, you'll need to call
437 /// [`ChannelMonitor::get_latest_holder_commitment_txn`] and broadcast the resulting
438 /// transactions once you've safely ensured no further channel updates can be generated by your
439 /// [`ChannelManager`].
441 /// Note that at least one final [`ChannelMonitorUpdate`] may still be provided, which must
442 /// still be processed by a running [`ChannelMonitor`]. This final update will mark the
443 /// [`ChannelMonitor`] as finalized, ensuring no further updates (e.g. revocation of the latest
444 /// commitment transaction) are allowed.
446 /// Note that even if you return a [`PermanentFailure`] due to unavailability of secondary
447 /// [`ChannelMonitor`] copies, you should still make an attempt to store the update where
448 /// possible to ensure you can claim HTLC outputs on the latest commitment transaction
449 /// broadcasted later.
451 /// In case of distributed watchtowers deployment, the new version must be written to disk, as
452 /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
453 /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
454 /// lagging behind on block processing.
456 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
457 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
460 use lightning::chain::ChannelMonitorUpdateStatus as ChannelMonitorUpdateStatusImport;
461 pub(crate) type nativeChannelMonitorUpdateStatus = ChannelMonitorUpdateStatusImport;
463 impl ChannelMonitorUpdateStatus {
465 pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateStatus {
467 ChannelMonitorUpdateStatus::Completed => nativeChannelMonitorUpdateStatus::Completed,
468 ChannelMonitorUpdateStatus::InProgress => nativeChannelMonitorUpdateStatus::InProgress,
469 ChannelMonitorUpdateStatus::PermanentFailure => nativeChannelMonitorUpdateStatus::PermanentFailure,
473 pub(crate) fn into_native(self) -> nativeChannelMonitorUpdateStatus {
475 ChannelMonitorUpdateStatus::Completed => nativeChannelMonitorUpdateStatus::Completed,
476 ChannelMonitorUpdateStatus::InProgress => nativeChannelMonitorUpdateStatus::InProgress,
477 ChannelMonitorUpdateStatus::PermanentFailure => nativeChannelMonitorUpdateStatus::PermanentFailure,
481 pub(crate) fn from_native(native: &nativeChannelMonitorUpdateStatus) -> Self {
483 nativeChannelMonitorUpdateStatus::Completed => ChannelMonitorUpdateStatus::Completed,
484 nativeChannelMonitorUpdateStatus::InProgress => ChannelMonitorUpdateStatus::InProgress,
485 nativeChannelMonitorUpdateStatus::PermanentFailure => ChannelMonitorUpdateStatus::PermanentFailure,
489 pub(crate) fn native_into(native: nativeChannelMonitorUpdateStatus) -> Self {
491 nativeChannelMonitorUpdateStatus::Completed => ChannelMonitorUpdateStatus::Completed,
492 nativeChannelMonitorUpdateStatus::InProgress => ChannelMonitorUpdateStatus::InProgress,
493 nativeChannelMonitorUpdateStatus::PermanentFailure => ChannelMonitorUpdateStatus::PermanentFailure,
497 /// Creates a copy of the ChannelMonitorUpdateStatus
499 pub extern "C" fn ChannelMonitorUpdateStatus_clone(orig: &ChannelMonitorUpdateStatus) -> ChannelMonitorUpdateStatus {
503 /// Utility method to constructs a new Completed-variant ChannelMonitorUpdateStatus
504 pub extern "C" fn ChannelMonitorUpdateStatus_completed() -> ChannelMonitorUpdateStatus {
505 ChannelMonitorUpdateStatus::Completed}
507 /// Utility method to constructs a new InProgress-variant ChannelMonitorUpdateStatus
508 pub extern "C" fn ChannelMonitorUpdateStatus_in_progress() -> ChannelMonitorUpdateStatus {
509 ChannelMonitorUpdateStatus::InProgress}
511 /// Utility method to constructs a new PermanentFailure-variant ChannelMonitorUpdateStatus
512 pub extern "C" fn ChannelMonitorUpdateStatus_permanent_failure() -> ChannelMonitorUpdateStatus {
513 ChannelMonitorUpdateStatus::PermanentFailure}
514 /// Checks if two ChannelMonitorUpdateStatuss contain equal inner contents.
515 /// This ignores pointers and is_owned flags and looks at the values in fields.
517 pub extern "C" fn ChannelMonitorUpdateStatus_eq(a: &ChannelMonitorUpdateStatus, b: &ChannelMonitorUpdateStatus) -> bool {
518 if &a.to_native() == &b.to_native() { true } else { false }
520 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
521 /// blocks are connected and disconnected.
523 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
524 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
525 /// channel state changes and HTLCs are resolved. See method documentation for specific
528 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
529 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
530 /// without taking any further action such as persisting the current state.
532 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
533 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
534 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
535 /// funds in the channel. See [`ChannelMonitorUpdateStatus`] for more details about how to handle
536 /// multiple instances.
538 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
541 /// An opaque pointer which is passed to your function implementations as an argument.
542 /// This has no meaning in the LDK, and can be NULL or any other value.
543 pub this_arg: *mut c_void,
544 /// Watches a channel identified by `funding_txo` using `monitor`.
546 /// Implementations are responsible for watching the chain for the funding transaction along
547 /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
548 /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
550 /// Note: this interface MUST error with [`ChannelMonitorUpdateStatus::PermanentFailure`] if
551 /// the given `funding_txo` has previously been registered via `watch_channel`.
553 /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
554 /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
555 /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
556 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,
557 /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
559 /// Implementations must call [`update_monitor`] with the given update. See
560 /// [`ChannelMonitorUpdateStatus`] for invariants around returning an error.
562 /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
563 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,
564 /// Returns any monitor events since the last call. Subsequent calls must only return new
567 /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
568 /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
571 /// For details on asynchronous [`ChannelMonitor`] updating and returning
572 /// [`MonitorEvent::Completed`] here, see [`ChannelMonitorUpdateStatus::InProgress`].
573 pub release_pending_monitor_events: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C3Tuple_OutPointCVec_MonitorEventZPublicKeyZZ,
574 /// Frees any resources associated with this object given its this_arg pointer.
575 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
576 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
578 unsafe impl Send for Watch {}
579 unsafe impl Sync for Watch {}
581 pub(crate) extern "C" fn Watch_clone_fields(orig: &Watch) -> Watch {
583 this_arg: orig.this_arg,
584 watch_channel: Clone::clone(&orig.watch_channel),
585 update_channel: Clone::clone(&orig.update_channel),
586 release_pending_monitor_events: Clone::clone(&orig.release_pending_monitor_events),
587 free: Clone::clone(&orig.free),
591 use lightning::chain::Watch as rustWatch;
592 impl rustWatch<crate::lightning::sign::WriteableEcdsaChannelSigner> for Watch {
593 fn watch_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut monitor: lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::sign::WriteableEcdsaChannelSigner>) -> lightning::chain::ChannelMonitorUpdateStatus {
594 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 });
597 fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: &lightning::chain::channelmonitor::ChannelMonitorUpdate) -> lightning::chain::ChannelMonitorUpdateStatus {
598 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: unsafe { ObjOps::nonnull_ptr_to_inner((update as *const lightning::chain::channelmonitor::ChannelMonitorUpdate<>) as *mut _) }, is_owned: false });
601 fn release_pending_monitor_events(&self) -> Vec<(lightning::chain::transaction::OutPoint, Vec<lightning::chain::channelmonitor::MonitorEvent>, Option<bitcoin::secp256k1::PublicKey>)> {
602 let mut ret = (self.release_pending_monitor_events)(self.this_arg);
603 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 }); };
608 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
609 // directly as a Deref trait in higher-level structs:
610 impl core::ops::Deref for Watch {
612 fn deref(&self) -> &Self {
616 /// Calls the free function if one is set
618 pub extern "C" fn Watch_free(this_ptr: Watch) { }
619 impl Drop for Watch {
621 if let Some(f) = self.free {
626 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
629 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
630 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
631 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
632 /// receiving full blocks from a chain source, any further filtering is unnecessary.
634 /// After an output has been registered, subsequent block retrievals from the chain source must not
635 /// exclude any transactions matching the new criteria nor any in-block descendants of such
638 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
639 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
640 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
641 /// invocation that has called the `Filter` must return [`InProgress`].
643 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
644 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
645 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
648 /// An opaque pointer which is passed to your function implementations as an argument.
649 /// This has no meaning in the LDK, and can be NULL or any other value.
650 pub this_arg: *mut c_void,
651 /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
652 /// a spending condition.
653 pub register_tx: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32], script_pubkey: crate::c_types::u8slice),
654 /// Registers interest in spends of a transaction output.
656 /// Note that this method might be called during processing of a new block. You therefore need
657 /// to ensure that also dependent output spents within an already connected block are correctly
658 /// handled, e.g., by re-scanning the block in question whenever new outputs have been
659 /// registered mid-processing.
660 pub register_output: extern "C" fn (this_arg: *const c_void, output: crate::lightning::chain::WatchedOutput),
661 /// Frees any resources associated with this object given its this_arg pointer.
662 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
663 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
665 unsafe impl Send for Filter {}
666 unsafe impl Sync for Filter {}
668 pub(crate) extern "C" fn Filter_clone_fields(orig: &Filter) -> Filter {
670 this_arg: orig.this_arg,
671 register_tx: Clone::clone(&orig.register_tx),
672 register_output: Clone::clone(&orig.register_output),
673 free: Clone::clone(&orig.free),
677 use lightning::chain::Filter as rustFilter;
678 impl rustFilter for Filter {
679 fn register_tx(&self, mut txid: &bitcoin::hash_types::Txid, mut script_pubkey: &bitcoin::blockdata::script::Script) {
680 (self.register_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pubkey[..]))
682 fn register_output(&self, mut output: lightning::chain::WatchedOutput) {
683 (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: ObjOps::heap_alloc(output), is_owned: true })
687 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
688 // directly as a Deref trait in higher-level structs:
689 impl core::ops::Deref for Filter {
691 fn deref(&self) -> &Self {
695 /// Calls the free function if one is set
697 pub extern "C" fn Filter_free(this_ptr: Filter) { }
698 impl Drop for Filter {
700 if let Some(f) = self.free {
706 use lightning::chain::WatchedOutput as nativeWatchedOutputImport;
707 pub(crate) type nativeWatchedOutput = nativeWatchedOutputImport;
709 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
711 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
712 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
713 /// [`Confirm::transactions_confirmed`].
715 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
716 /// may have been spent there. See [`Filter::register_output`] for details.
718 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
719 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
722 pub struct WatchedOutput {
723 /// A pointer to the opaque Rust object.
725 /// Nearly everywhere, inner must be non-null, however in places where
726 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
727 pub inner: *mut nativeWatchedOutput,
728 /// Indicates that this is the only struct which contains the same pointer.
730 /// Rust functions which take ownership of an object provided via an argument require
731 /// this to be true and invalidate the object pointed to by inner.
735 impl Drop for WatchedOutput {
737 if self.is_owned && !<*mut nativeWatchedOutput>::is_null(self.inner) {
738 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
742 /// Frees any resources used by the WatchedOutput, if is_owned is set and inner is non-NULL.
744 pub extern "C" fn WatchedOutput_free(this_obj: WatchedOutput) { }
746 /// Used only if an object of this type is returned as a trait impl by a method
747 pub(crate) extern "C" fn WatchedOutput_free_void(this_ptr: *mut c_void) {
748 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeWatchedOutput) };
752 pub(crate) fn get_native_ref(&self) -> &'static nativeWatchedOutput {
753 unsafe { &*ObjOps::untweak_ptr(self.inner) }
755 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeWatchedOutput {
756 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
758 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
759 pub(crate) fn take_inner(mut self) -> *mut nativeWatchedOutput {
760 assert!(self.is_owned);
761 let ret = ObjOps::untweak_ptr(self.inner);
762 self.inner = core::ptr::null_mut();
766 /// First block where the transaction output may have been spent.
768 pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crate::c_types::derived::COption_BlockHashZ {
769 let mut inner_val = &mut this_ptr.get_native_mut_ref().block_hash;
770 let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_BlockHashZ::None } else { crate::c_types::derived::COption_BlockHashZ::Some(/* WARNING: CLONING CONVERSION HERE! &Option<Enum> is otherwise un-expressable. */ { crate::c_types::ThirtyTwoBytes { data: (*inner_val.as_ref().unwrap()).clone().into_inner() } }) };
773 /// First block where the transaction output may have been spent.
775 pub extern "C" fn WatchedOutput_set_block_hash(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::COption_BlockHashZ) {
776 let mut local_val = { /*val*/ let val_opt = val; if val_opt.is_none() { None } else { Some({ { ::bitcoin::hash_types::BlockHash::from_slice(&{ val_opt.take() }.data[..]).unwrap() }})} };
777 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.block_hash = local_val;
779 /// Outpoint identifying the transaction output.
781 pub extern "C" fn WatchedOutput_get_outpoint(this_ptr: &WatchedOutput) -> crate::lightning::chain::transaction::OutPoint {
782 let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint;
783 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 }
785 /// Outpoint identifying the transaction output.
787 pub extern "C" fn WatchedOutput_set_outpoint(this_ptr: &mut WatchedOutput, mut val: crate::lightning::chain::transaction::OutPoint) {
788 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
790 /// Spending condition of the transaction output.
792 pub extern "C" fn WatchedOutput_get_script_pubkey(this_ptr: &WatchedOutput) -> crate::c_types::u8slice {
793 let mut inner_val = &mut this_ptr.get_native_mut_ref().script_pubkey;
794 crate::c_types::u8slice::from_slice(&inner_val[..])
796 /// Spending condition of the transaction output.
798 pub extern "C" fn WatchedOutput_set_script_pubkey(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::CVec_u8Z) {
799 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.script_pubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust());
801 /// Constructs a new WatchedOutput given each field
804 pub extern "C" fn WatchedOutput_new(mut block_hash_arg: crate::c_types::derived::COption_BlockHashZ, mut outpoint_arg: crate::lightning::chain::transaction::OutPoint, mut script_pubkey_arg: crate::c_types::derived::CVec_u8Z) -> WatchedOutput {
805 let mut local_block_hash_arg = { /*block_hash_arg*/ let block_hash_arg_opt = block_hash_arg; if block_hash_arg_opt.is_none() { None } else { Some({ { ::bitcoin::hash_types::BlockHash::from_slice(&{ block_hash_arg_opt.take() }.data[..]).unwrap() }})} };
806 WatchedOutput { inner: ObjOps::heap_alloc(nativeWatchedOutput {
807 block_hash: local_block_hash_arg,
808 outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
809 script_pubkey: ::bitcoin::blockdata::script::Script::from(script_pubkey_arg.into_rust()),
812 impl Clone for WatchedOutput {
813 fn clone(&self) -> Self {
815 inner: if <*mut nativeWatchedOutput>::is_null(self.inner) { core::ptr::null_mut() } else {
816 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
822 /// Used only if an object of this type is returned as a trait impl by a method
823 pub(crate) extern "C" fn WatchedOutput_clone_void(this_ptr: *const c_void) -> *mut c_void {
824 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeWatchedOutput)).clone() })) as *mut c_void
827 /// Creates a copy of the WatchedOutput
828 pub extern "C" fn WatchedOutput_clone(orig: &WatchedOutput) -> WatchedOutput {
831 /// Checks if two WatchedOutputs contain equal inner contents.
832 /// This ignores pointers and is_owned flags and looks at the values in fields.
833 /// Two objects with NULL inner values will be considered "equal" here.
835 pub extern "C" fn WatchedOutput_eq(a: &WatchedOutput, b: &WatchedOutput) -> bool {
836 if a.inner == b.inner { return true; }
837 if a.inner.is_null() || b.inner.is_null() { return false; }
838 if a.get_native_ref() == b.get_native_ref() { true } else { false }
840 /// Generates a non-cryptographic 64-bit hash of the WatchedOutput.
842 pub extern "C" fn WatchedOutput_hash(o: &WatchedOutput) -> u64 {
843 if o.inner.is_null() { return 0; }
844 // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
846 let mut hasher = core::hash::SipHasher::new();
847 core::hash::Hash::hash(o.get_native_ref(), &mut hasher);
848 core::hash::Hasher::finish(&hasher)