Update auto-generated bindings
[ldk-c-bindings] / lightning-c-bindings / src / lightning / chain / mod.rs
1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
3 //
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.
8
9 //! Structs and traits which allow other parts of rust-lightning to interact with the blockchain.
10
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};
18
19 pub mod chaininterface;
20 pub mod chainmonitor;
21 pub mod channelmonitor;
22 pub mod transaction;
23 pub mod keysinterface;
24 mod onchaintx {
25
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};
33
34 }
35 mod package {
36
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};
44
45 }
46
47 use lightning::chain::BestBlock as nativeBestBlockImport;
48 pub(crate) type nativeBestBlock = nativeBestBlockImport;
49
50 /// The best known block as identified by its hash and height.
51 #[must_use]
52 #[repr(C)]
53 pub struct BestBlock {
54         /// A pointer to the opaque Rust object.
55
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.
60
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.
63         pub is_owned: bool,
64 }
65
66 impl Drop for BestBlock {
67         fn drop(&mut self) {
68                 if self.is_owned && !<*mut nativeBestBlock>::is_null(self.inner) {
69                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
70                 }
71         }
72 }
73 /// Frees any resources used by the BestBlock, if is_owned is set and inner is non-NULL.
74 #[no_mangle]
75 pub extern "C" fn BestBlock_free(this_obj: BestBlock) { }
76 #[allow(unused)]
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); }
80 }
81 #[allow(unused)]
82 impl BestBlock {
83         pub(crate) fn get_native_ref(&self) -> &'static nativeBestBlock {
84                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
85         }
86         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBestBlock {
87                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
88         }
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();
94                 ret
95         }
96 }
97 impl Clone for BestBlock {
98         fn clone(&self) -> Self {
99                 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()) },
102                         is_owned: true,
103                 }
104         }
105 }
106 #[allow(unused)]
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
110 }
111 #[no_mangle]
112 /// Creates a copy of the BestBlock
113 pub extern "C" fn BestBlock_clone(orig: &BestBlock) -> BestBlock {
114         orig.clone()
115 }
116 /// Constructs a `BestBlock` that represents the genesis block at height 0 of the given
117 /// network.
118 #[must_use]
119 #[no_mangle]
120 pub extern "C" fn BestBlock_from_genesis(mut network: crate::bitcoin::network::Network) -> BestBlock {
121         let mut ret = lightning::chain::BestBlock::from_genesis(network.into_bitcoin());
122         BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
123 }
124
125 /// Returns a `BestBlock` as identified by the given block hash and height.
126 #[must_use]
127 #[no_mangle]
128 pub extern "C" fn BestBlock_new(mut block_hash: crate::c_types::ThirtyTwoBytes, mut height: u32) -> BestBlock {
129         let mut ret = lightning::chain::BestBlock::new(::bitcoin::hash_types::BlockHash::from_slice(&block_hash.data[..]).unwrap(), height);
130         BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
131 }
132
133 /// Returns the best block hash.
134 #[must_use]
135 #[no_mangle]
136 pub extern "C" fn BestBlock_block_hash(this_arg: &BestBlock) -> crate::c_types::ThirtyTwoBytes {
137         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_hash();
138         crate::c_types::ThirtyTwoBytes { data: ret.into_inner() }
139 }
140
141 /// Returns the best block height.
142 #[must_use]
143 #[no_mangle]
144 pub extern "C" fn BestBlock_height(this_arg: &BestBlock) -> u32 {
145         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.height();
146         ret
147 }
148
149 /// An error when accessing the chain via [`Access`].
150 #[must_use]
151 #[derive(Clone)]
152 #[repr(C)]
153 pub enum AccessError {
154         /// The requested chain is unknown.
155         UnknownChain,
156         /// The requested transaction doesn't exist or hasn't confirmed.
157         UnknownTx,
158 }
159 use lightning::chain::AccessError as nativeAccessError;
160 impl AccessError {
161         #[allow(unused)]
162         pub(crate) fn to_native(&self) -> nativeAccessError {
163                 match self {
164                         AccessError::UnknownChain => nativeAccessError::UnknownChain,
165                         AccessError::UnknownTx => nativeAccessError::UnknownTx,
166                 }
167         }
168         #[allow(unused)]
169         pub(crate) fn into_native(self) -> nativeAccessError {
170                 match self {
171                         AccessError::UnknownChain => nativeAccessError::UnknownChain,
172                         AccessError::UnknownTx => nativeAccessError::UnknownTx,
173                 }
174         }
175         #[allow(unused)]
176         pub(crate) fn from_native(native: &nativeAccessError) -> Self {
177                 match native {
178                         nativeAccessError::UnknownChain => AccessError::UnknownChain,
179                         nativeAccessError::UnknownTx => AccessError::UnknownTx,
180                 }
181         }
182         #[allow(unused)]
183         pub(crate) fn native_into(native: nativeAccessError) -> Self {
184                 match native {
185                         nativeAccessError::UnknownChain => AccessError::UnknownChain,
186                         nativeAccessError::UnknownTx => AccessError::UnknownTx,
187                 }
188         }
189 }
190 /// Creates a copy of the AccessError
191 #[no_mangle]
192 pub extern "C" fn AccessError_clone(orig: &AccessError) -> AccessError {
193         orig.clone()
194 }
195 #[no_mangle]
196 /// Utility method to constructs a new UnknownChain-variant AccessError
197 pub extern "C" fn AccessError_unknown_chain() -> AccessError {
198         AccessError::UnknownChain}
199 #[no_mangle]
200 /// Utility method to constructs a new UnknownTx-variant AccessError
201 pub extern "C" fn AccessError_unknown_tx() -> AccessError {
202         AccessError::UnknownTx}
203 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
204 /// UTXOs.
205 #[repr(C)]
206 pub struct Access {
207         /// An opaque pointer which is passed to your function implementations as an argument.
208         /// This has no meaning in the LDK, and can be NULL or any other value.
209         pub this_arg: *mut c_void,
210         /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
211         /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
212         /// is unknown.
213         ///
214         /// [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
215         #[must_use]
216         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,
217         /// Frees any resources associated with this object given its this_arg pointer.
218         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
219         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
220 }
221 unsafe impl Send for Access {}
222 unsafe impl Sync for Access {}
223 #[no_mangle]
224 pub(crate) extern "C" fn Access_clone_fields(orig: &Access) -> Access {
225         Access {
226                 this_arg: orig.this_arg,
227                 get_utxo: Clone::clone(&orig.get_utxo),
228                 free: Clone::clone(&orig.free),
229         }
230 }
231
232 use lightning::chain::Access as rustAccess;
233 impl rustAccess for Access {
234         fn get_utxo(&self, mut genesis_hash: &bitcoin::hash_types::BlockHash, mut short_channel_id: u64) -> Result<bitcoin::blockdata::transaction::TxOut, lightning::chain::AccessError> {
235                 let mut ret = (self.get_utxo)(self.this_arg, genesis_hash.as_inner(), short_channel_id);
236                 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() })};
237                 local_ret
238         }
239 }
240
241 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
242 // directly as a Deref trait in higher-level structs:
243 impl core::ops::Deref for Access {
244         type Target = Self;
245         fn deref(&self) -> &Self {
246                 self
247         }
248 }
249 /// Calls the free function if one is set
250 #[no_mangle]
251 pub extern "C" fn Access_free(this_ptr: Access) { }
252 impl Drop for Access {
253         fn drop(&mut self) {
254                 if let Some(f) = self.free {
255                         f(self.this_arg);
256                 }
257         }
258 }
259 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
260 /// chain.
261 ///
262 /// Useful when needing to replay chain data upon startup or as new chain events occur. Clients
263 /// sourcing chain data using a block-oriented API should prefer this interface over [`Confirm`].
264 /// Such clients fetch the entire header chain whereas clients using [`Confirm`] only fetch headers
265 /// when needed.
266 #[repr(C)]
267 pub struct Listen {
268         /// An opaque pointer which is passed to your function implementations as an argument.
269         /// This has no meaning in the LDK, and can be NULL or any other value.
270         pub this_arg: *mut c_void,
271         /// Notifies the listener that a block was added at the given height.
272         pub block_connected: extern "C" fn (this_arg: *const c_void, block: crate::c_types::u8slice, height: u32),
273         /// Notifies the listener that a block was removed at the given height.
274         pub block_disconnected: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
275         /// Frees any resources associated with this object given its this_arg pointer.
276         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
277         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
278 }
279 unsafe impl Send for Listen {}
280 unsafe impl Sync for Listen {}
281 #[no_mangle]
282 pub(crate) extern "C" fn Listen_clone_fields(orig: &Listen) -> Listen {
283         Listen {
284                 this_arg: orig.this_arg,
285                 block_connected: Clone::clone(&orig.block_connected),
286                 block_disconnected: Clone::clone(&orig.block_disconnected),
287                 free: Clone::clone(&orig.free),
288         }
289 }
290
291 use lightning::chain::Listen as rustListen;
292 impl rustListen for Listen {
293         fn block_connected(&self, mut block: &bitcoin::blockdata::block::Block, mut height: u32) {
294                 let mut local_block = ::bitcoin::consensus::encode::serialize(block);
295                 (self.block_connected)(self.this_arg, crate::c_types::u8slice::from_slice(&local_block), height)
296         }
297         fn block_disconnected(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
298                 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
299                 (self.block_disconnected)(self.this_arg, &local_header, height)
300         }
301 }
302
303 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
304 // directly as a Deref trait in higher-level structs:
305 impl core::ops::Deref for Listen {
306         type Target = Self;
307         fn deref(&self) -> &Self {
308                 self
309         }
310 }
311 /// Calls the free function if one is set
312 #[no_mangle]
313 pub extern "C" fn Listen_free(this_ptr: Listen) { }
314 impl Drop for Listen {
315         fn drop(&mut self) {
316                 if let Some(f) = self.free {
317                         f(self.this_arg);
318                 }
319         }
320 }
321 /// The `Confirm` trait is used to notify when transactions have been confirmed on chain or
322 /// unconfirmed during a chain reorganization.
323 ///
324 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
325 /// [`Listen`]. For instance, an Electrum client may implement [`Filter`] by subscribing to activity
326 /// related to registered transactions and outputs. Upon notification, it would pass along the
327 /// matching transactions using this interface.
328 ///
329 /// # Use
330 ///
331 /// The intended use is as follows:
332 /// - Call [`transactions_confirmed`] to process any on-chain activity of interest.
333 /// - Call [`transaction_unconfirmed`] to process any transaction returned by [`get_relevant_txids`]
334 ///   that has been reorganized out of the chain.
335 /// - Call [`best_block_updated`] whenever a new chain tip becomes available.
336 ///
337 /// # Order
338 ///
339 /// Clients must call these methods in chain order. Specifically:
340 /// - Transactions confirmed in a block must be given before transactions confirmed in a later
341 ///   block.
342 /// - Dependent transactions within the same block must be given in topological order, possibly in
343 ///   separate calls.
344 /// - Unconfirmed transactions must be given after the original confirmations and before any
345 ///   reconfirmation.
346 ///
347 /// See individual method documentation for further details.
348 ///
349 /// [`transactions_confirmed`]: Self::transactions_confirmed
350 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
351 /// [`best_block_updated`]: Self::best_block_updated
352 /// [`get_relevant_txids`]: Self::get_relevant_txids
353 #[repr(C)]
354 pub struct Confirm {
355         /// An opaque pointer which is passed to your function implementations as an argument.
356         /// This has no meaning in the LDK, and can be NULL or any other value.
357         pub this_arg: *mut c_void,
358         /// Processes transactions confirmed in a block with a given header and height.
359         ///
360         /// Should be called for any transactions registered by [`Filter::register_tx`] or any
361         /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
362         /// appearing in the same block do not need to be included in the same call; instead, multiple
363         /// calls with additional transactions may be made so long as they are made in [chain order].
364         ///
365         /// May be called before or after [`best_block_updated`] for the corresponding block. However,
366         /// in the event of a chain reorganization, it must not be called with a `header` that is no
367         /// longer in the chain as of the last call to [`best_block_updated`].
368         ///
369         /// [chain order]: Confirm#Order
370         /// [`best_block_updated`]: Self::best_block_updated
371         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),
372         /// Processes a transaction that is no longer confirmed as result of a chain reorganization.
373         ///
374         /// Should be called for any transaction returned by [`get_relevant_txids`] if it has been
375         /// reorganized out of the best chain. Once called, the given transaction should not be returned
376         /// by [`get_relevant_txids`] unless it has been reconfirmed via [`transactions_confirmed`].
377         ///
378         /// [`get_relevant_txids`]: Self::get_relevant_txids
379         /// [`transactions_confirmed`]: Self::transactions_confirmed
380         pub transaction_unconfirmed: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32]),
381         /// Processes an update to the best header connected at the given height.
382         ///
383         /// Should be called when a new header is available but may be skipped for intermediary blocks
384         /// if they become available at the same time.
385         pub best_block_updated: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
386         /// Returns transactions that should be monitored for reorganization out of the chain.
387         ///
388         /// Should include any transactions passed to [`transactions_confirmed`] that have insufficient
389         /// confirmations to be safe from a chain reorganization. Should not include any transactions
390         /// passed to [`transaction_unconfirmed`] unless later reconfirmed.
391         ///
392         /// May be called to determine the subset of transactions that must still be monitored for
393         /// reorganization. Will be idempotent between calls but may change as a result of calls to the
394         /// other interface methods. Thus, this is useful to determine which transactions may need to be
395         /// given to [`transaction_unconfirmed`].
396         ///
397         /// [`transactions_confirmed`]: Self::transactions_confirmed
398         /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
399         #[must_use]
400         pub get_relevant_txids: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_TxidZ,
401         /// Frees any resources associated with this object given its this_arg pointer.
402         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
403         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
404 }
405 unsafe impl Send for Confirm {}
406 unsafe impl Sync for Confirm {}
407 #[no_mangle]
408 pub(crate) extern "C" fn Confirm_clone_fields(orig: &Confirm) -> Confirm {
409         Confirm {
410                 this_arg: orig.this_arg,
411                 transactions_confirmed: Clone::clone(&orig.transactions_confirmed),
412                 transaction_unconfirmed: Clone::clone(&orig.transaction_unconfirmed),
413                 best_block_updated: Clone::clone(&orig.best_block_updated),
414                 get_relevant_txids: Clone::clone(&orig.get_relevant_txids),
415                 free: Clone::clone(&orig.free),
416         }
417 }
418
419 use lightning::chain::Confirm as rustConfirm;
420 impl rustConfirm for Confirm {
421         fn transactions_confirmed(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut txdata: &lightning::chain::transaction::TransactionData, mut height: u32) {
422                 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
423                 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 }); };
424                 (self.transactions_confirmed)(self.this_arg, &local_header, local_txdata.into(), height)
425         }
426         fn transaction_unconfirmed(&self, mut txid: &bitcoin::hash_types::Txid) {
427                 (self.transaction_unconfirmed)(self.this_arg, txid.as_inner())
428         }
429         fn best_block_updated(&self, mut header: &bitcoin::blockdata::block::BlockHeader, mut height: u32) {
430                 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
431                 (self.best_block_updated)(self.this_arg, &local_header, height)
432         }
433         fn get_relevant_txids(&self) -> Vec<bitcoin::hash_types::Txid> {
434                 let mut ret = (self.get_relevant_txids)(self.this_arg);
435                 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() }); };
436                 local_ret
437         }
438 }
439
440 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
441 // directly as a Deref trait in higher-level structs:
442 impl core::ops::Deref for Confirm {
443         type Target = Self;
444         fn deref(&self) -> &Self {
445                 self
446         }
447 }
448 /// Calls the free function if one is set
449 #[no_mangle]
450 pub extern "C" fn Confirm_free(this_ptr: Confirm) { }
451 impl Drop for Confirm {
452         fn drop(&mut self) {
453                 if let Some(f) = self.free {
454                         f(self.this_arg);
455                 }
456         }
457 }
458 /// An error enum representing a failure to persist a channel monitor update.
459 #[must_use]
460 #[derive(Clone)]
461 #[repr(C)]
462 pub enum ChannelMonitorUpdateErr {
463         /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
464         /// our state failed, but is expected to succeed at some point in the future).
465         ///
466         /// Such a failure will \"freeze\" a channel, preventing us from revoking old states or
467         /// submitting new commitment transactions to the counterparty. Once the update(s) that failed
468         /// have been successfully applied, a [`MonitorEvent::UpdateCompleted`] event should be returned
469         /// via [`Watch::release_pending_monitor_events`] which will then restore the channel to an
470         /// operational state.
471         ///
472         /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
473         /// you return a TemporaryFailure you must ensure that it is written to disk safely before
474         /// writing out the latest ChannelManager state.
475         ///
476         /// Even when a channel has been \"frozen\" updates to the ChannelMonitor can continue to occur
477         /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
478         /// to claim it on this channel) and those updates must be applied wherever they can be. At
479         /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
480         /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
481         /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
482         /// been \"frozen\".
483         ///
484         /// Note that even if updates made after TemporaryFailure succeed you must still provide a
485         /// [`MonitorEvent::UpdateCompleted`] to ensure you have the latest monitor and re-enable
486         /// normal channel operation. Note that this is normally generated through a call to
487         /// [`ChainMonitor::channel_monitor_updated`].
488         ///
489         /// Note that the update being processed here will not be replayed for you when you return a
490         /// [`MonitorEvent::UpdateCompleted`] event via [`Watch::release_pending_monitor_events`], so
491         /// you must store the update itself on your own local disk prior to returning a
492         /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
493         /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
494         /// reload-time.
495         ///
496         /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
497         /// remote location (with local copies persisted immediately), it is anticipated that all
498         /// updates will return TemporaryFailure until the remote copies could be updated.
499         ///
500         /// [`ChainMonitor::channel_monitor_updated`]: chainmonitor::ChainMonitor::channel_monitor_updated
501         TemporaryFailure,
502         /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
503         /// different watchtower and cannot update with all watchtowers that were previously informed
504         /// of this channel).
505         ///
506         /// At reception of this error, ChannelManager will force-close the channel and return at
507         /// least a final ChannelMonitorUpdate::ChannelForceClosed which must be delivered to at
508         /// least one ChannelMonitor copy. Revocation secret MUST NOT be released and offchain channel
509         /// update must be rejected.
510         ///
511         /// This failure may also signal a failure to update the local persisted copy of one of
512         /// the channel monitor instance.
513         ///
514         /// Note that even when you fail a holder commitment transaction update, you must store the
515         /// update to ensure you can claim from it in case of a duplicate copy of this ChannelMonitor
516         /// broadcasts it (e.g distributed channel-monitor deployment)
517         ///
518         /// In case of distributed watchtowers deployment, the new version must be written to disk, as
519         /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
520         /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
521         /// lagging behind on block processing.
522         PermanentFailure,
523 }
524 use lightning::chain::ChannelMonitorUpdateErr as nativeChannelMonitorUpdateErr;
525 impl ChannelMonitorUpdateErr {
526         #[allow(unused)]
527         pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateErr {
528                 match self {
529                         ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
530                         ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
531                 }
532         }
533         #[allow(unused)]
534         pub(crate) fn into_native(self) -> nativeChannelMonitorUpdateErr {
535                 match self {
536                         ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
537                         ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
538                 }
539         }
540         #[allow(unused)]
541         pub(crate) fn from_native(native: &nativeChannelMonitorUpdateErr) -> Self {
542                 match native {
543                         nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
544                         nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
545                 }
546         }
547         #[allow(unused)]
548         pub(crate) fn native_into(native: nativeChannelMonitorUpdateErr) -> Self {
549                 match native {
550                         nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
551                         nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
552                 }
553         }
554 }
555 /// Creates a copy of the ChannelMonitorUpdateErr
556 #[no_mangle]
557 pub extern "C" fn ChannelMonitorUpdateErr_clone(orig: &ChannelMonitorUpdateErr) -> ChannelMonitorUpdateErr {
558         orig.clone()
559 }
560 #[no_mangle]
561 /// Utility method to constructs a new TemporaryFailure-variant ChannelMonitorUpdateErr
562 pub extern "C" fn ChannelMonitorUpdateErr_temporary_failure() -> ChannelMonitorUpdateErr {
563         ChannelMonitorUpdateErr::TemporaryFailure}
564 #[no_mangle]
565 /// Utility method to constructs a new PermanentFailure-variant ChannelMonitorUpdateErr
566 pub extern "C" fn ChannelMonitorUpdateErr_permanent_failure() -> ChannelMonitorUpdateErr {
567         ChannelMonitorUpdateErr::PermanentFailure}
568 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
569 /// blocks are connected and disconnected.
570 ///
571 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
572 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
573 /// channel state changes and HTLCs are resolved. See method documentation for specific
574 /// requirements.
575 ///
576 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
577 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
578 /// without taking any further action such as persisting the current state.
579 ///
580 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
581 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
582 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
583 /// funds in the channel. See [`ChannelMonitorUpdateErr`] for more details about how to handle
584 /// multiple instances.
585 ///
586 /// [`PermanentFailure`]: ChannelMonitorUpdateErr::PermanentFailure
587 #[repr(C)]
588 pub struct Watch {
589         /// An opaque pointer which is passed to your function implementations as an argument.
590         /// This has no meaning in the LDK, and can be NULL or any other value.
591         pub this_arg: *mut c_void,
592         /// Watches a channel identified by `funding_txo` using `monitor`.
593         ///
594         /// Implementations are responsible for watching the chain for the funding transaction along
595         /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
596         /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
597         ///
598         /// Note: this interface MUST error with `ChannelMonitorUpdateErr::PermanentFailure` if
599         /// the given `funding_txo` has previously been registered via `watch_channel`.
600         ///
601         /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
602         /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
603         /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
604         #[must_use]
605         pub watch_channel: extern "C" fn (this_arg: *const c_void, funding_txo: crate::lightning::chain::transaction::OutPoint, monitor: crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ,
606         /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
607         ///
608         /// Implementations must call [`update_monitor`] with the given update. See
609         /// [`ChannelMonitorUpdateErr`] for invariants around returning an error.
610         ///
611         /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
612         #[must_use]
613         pub update_channel: extern "C" fn (this_arg: *const c_void, funding_txo: crate::lightning::chain::transaction::OutPoint, update: crate::lightning::chain::channelmonitor::ChannelMonitorUpdate) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ,
614         /// Returns any monitor events since the last call. Subsequent calls must only return new
615         /// events.
616         ///
617         /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
618         /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
619         /// to disk.
620         ///
621         /// For details on asynchronous [`ChannelMonitor`] updating and returning
622         /// [`MonitorEvent::UpdateCompleted`] here, see [`ChannelMonitorUpdateErr::TemporaryFailure`].
623         #[must_use]
624         pub release_pending_monitor_events: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_MonitorEventZ,
625         /// Frees any resources associated with this object given its this_arg pointer.
626         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
627         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
628 }
629 unsafe impl Send for Watch {}
630 unsafe impl Sync for Watch {}
631 #[no_mangle]
632 pub(crate) extern "C" fn Watch_clone_fields(orig: &Watch) -> Watch {
633         Watch {
634                 this_arg: orig.this_arg,
635                 watch_channel: Clone::clone(&orig.watch_channel),
636                 update_channel: Clone::clone(&orig.update_channel),
637                 release_pending_monitor_events: Clone::clone(&orig.release_pending_monitor_events),
638                 free: Clone::clone(&orig.free),
639         }
640 }
641
642 use lightning::chain::Watch as rustWatch;
643 impl rustWatch<crate::lightning::chain::keysinterface::Sign> for Watch {
644         fn watch_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut monitor: lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::chain::keysinterface::Sign>) -> Result<(), lightning::chain::ChannelMonitorUpdateErr> {
645                 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 });
646                 let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
647                 local_ret
648         }
649         fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: lightning::chain::channelmonitor::ChannelMonitorUpdate) -> Result<(), lightning::chain::ChannelMonitorUpdateErr> {
650                 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 });
651                 let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })};
652                 local_ret
653         }
654         fn release_pending_monitor_events(&self) -> Vec<lightning::chain::channelmonitor::MonitorEvent> {
655                 let mut ret = (self.release_pending_monitor_events)(self.this_arg);
656                 let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { item.into_native() }); };
657                 local_ret
658         }
659 }
660
661 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
662 // directly as a Deref trait in higher-level structs:
663 impl core::ops::Deref for Watch {
664         type Target = Self;
665         fn deref(&self) -> &Self {
666                 self
667         }
668 }
669 /// Calls the free function if one is set
670 #[no_mangle]
671 pub extern "C" fn Watch_free(this_ptr: Watch) { }
672 impl Drop for Watch {
673         fn drop(&mut self) {
674                 if let Some(f) = self.free {
675                         f(self.this_arg);
676                 }
677         }
678 }
679 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
680 /// channels.
681 ///
682 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
683 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
684 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
685 /// receiving full blocks from a chain source, any further filtering is unnecessary.
686 ///
687 /// After an output has been registered, subsequent block retrievals from the chain source must not
688 /// exclude any transactions matching the new criteria nor any in-block descendants of such
689 /// transactions.
690 ///
691 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
692 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
693 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
694 /// invocation that has called the `Filter` must return [`TemporaryFailure`].
695 ///
696 /// [`TemporaryFailure`]: ChannelMonitorUpdateErr::TemporaryFailure
697 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
698 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
699 #[repr(C)]
700 pub struct Filter {
701         /// An opaque pointer which is passed to your function implementations as an argument.
702         /// This has no meaning in the LDK, and can be NULL or any other value.
703         pub this_arg: *mut c_void,
704         /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
705         /// a spending condition.
706         pub register_tx: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32], script_pubkey: crate::c_types::u8slice),
707         /// Registers interest in spends of a transaction output.
708         ///
709         /// Optionally, when `output.block_hash` is set, should return any transaction spending the
710         /// output that is found in the corresponding block along with its index.
711         ///
712         /// This return value is useful for Electrum clients in order to supply in-block descendant
713         /// transactions which otherwise were not included. This is not necessary for other clients if
714         /// such descendant transactions were already included (e.g., when a BIP 157 client provides the
715         /// full block).
716         #[must_use]
717         pub register_output: extern "C" fn (this_arg: *const c_void, output: crate::lightning::chain::WatchedOutput) -> crate::c_types::derived::COption_C2Tuple_usizeTransactionZZ,
718         /// Frees any resources associated with this object given its this_arg pointer.
719         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
720         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
721 }
722 unsafe impl Send for Filter {}
723 unsafe impl Sync for Filter {}
724 #[no_mangle]
725 pub(crate) extern "C" fn Filter_clone_fields(orig: &Filter) -> Filter {
726         Filter {
727                 this_arg: orig.this_arg,
728                 register_tx: Clone::clone(&orig.register_tx),
729                 register_output: Clone::clone(&orig.register_output),
730                 free: Clone::clone(&orig.free),
731         }
732 }
733
734 use lightning::chain::Filter as rustFilter;
735 impl rustFilter for Filter {
736         fn register_tx(&self, mut txid: &bitcoin::hash_types::Txid, mut script_pubkey: &bitcoin::blockdata::script::Script) {
737                 (self.register_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pubkey[..]))
738         }
739         fn register_output(&self, mut output: lightning::chain::WatchedOutput) -> Option<(usize, bitcoin::blockdata::transaction::Transaction)> {
740                 let mut ret = (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: ObjOps::heap_alloc(output), is_owned: true });
741                 let mut local_ret = if ret.is_some() { Some( { let (mut orig_ret_0_0, mut orig_ret_0_1) = ret.take().to_rust(); let mut local_ret_0 = (orig_ret_0_0, orig_ret_0_1.into_bitcoin()); local_ret_0 }) } else { None };
742                 local_ret
743         }
744 }
745
746 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
747 // directly as a Deref trait in higher-level structs:
748 impl core::ops::Deref for Filter {
749         type Target = Self;
750         fn deref(&self) -> &Self {
751                 self
752         }
753 }
754 /// Calls the free function if one is set
755 #[no_mangle]
756 pub extern "C" fn Filter_free(this_ptr: Filter) { }
757 impl Drop for Filter {
758         fn drop(&mut self) {
759                 if let Some(f) = self.free {
760                         f(self.this_arg);
761                 }
762         }
763 }
764
765 use lightning::chain::WatchedOutput as nativeWatchedOutputImport;
766 pub(crate) type nativeWatchedOutput = nativeWatchedOutputImport;
767
768 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
769 ///
770 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
771 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
772 /// the return value of [`Filter::register_output`].
773 ///
774 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
775 /// may have been spent there. See [`Filter::register_output`] for details.
776 ///
777 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
778 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
779 #[must_use]
780 #[repr(C)]
781 pub struct WatchedOutput {
782         /// A pointer to the opaque Rust object.
783
784         /// Nearly everywhere, inner must be non-null, however in places where
785         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
786         pub inner: *mut nativeWatchedOutput,
787         /// Indicates that this is the only struct which contains the same pointer.
788
789         /// Rust functions which take ownership of an object provided via an argument require
790         /// this to be true and invalidate the object pointed to by inner.
791         pub is_owned: bool,
792 }
793
794 impl Drop for WatchedOutput {
795         fn drop(&mut self) {
796                 if self.is_owned && !<*mut nativeWatchedOutput>::is_null(self.inner) {
797                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
798                 }
799         }
800 }
801 /// Frees any resources used by the WatchedOutput, if is_owned is set and inner is non-NULL.
802 #[no_mangle]
803 pub extern "C" fn WatchedOutput_free(this_obj: WatchedOutput) { }
804 #[allow(unused)]
805 /// Used only if an object of this type is returned as a trait impl by a method
806 pub(crate) extern "C" fn WatchedOutput_free_void(this_ptr: *mut c_void) {
807         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeWatchedOutput); }
808 }
809 #[allow(unused)]
810 impl WatchedOutput {
811         pub(crate) fn get_native_ref(&self) -> &'static nativeWatchedOutput {
812                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
813         }
814         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeWatchedOutput {
815                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
816         }
817         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
818         pub(crate) fn take_inner(mut self) -> *mut nativeWatchedOutput {
819                 assert!(self.is_owned);
820                 let ret = ObjOps::untweak_ptr(self.inner);
821                 self.inner = core::ptr::null_mut();
822                 ret
823         }
824 }
825 /// First block where the transaction output may have been spent.
826 ///
827 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
828 #[no_mangle]
829 pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crate::c_types::ThirtyTwoBytes {
830         let mut inner_val = &mut this_ptr.get_native_mut_ref().block_hash;
831         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() } } };
832         local_inner_val
833 }
834 /// First block where the transaction output may have been spent.
835 ///
836 /// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None
837 #[no_mangle]
838 pub extern "C" fn WatchedOutput_set_block_hash(this_ptr: &mut WatchedOutput, mut val: crate::c_types::ThirtyTwoBytes) {
839         let mut local_val = if val.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap() }) };
840         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.block_hash = local_val;
841 }
842 /// Outpoint identifying the transaction output.
843 #[no_mangle]
844 pub extern "C" fn WatchedOutput_get_outpoint(this_ptr: &WatchedOutput) -> crate::lightning::chain::transaction::OutPoint {
845         let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint;
846         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 }
847 }
848 /// Outpoint identifying the transaction output.
849 #[no_mangle]
850 pub extern "C" fn WatchedOutput_set_outpoint(this_ptr: &mut WatchedOutput, mut val: crate::lightning::chain::transaction::OutPoint) {
851         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
852 }
853 /// Spending condition of the transaction output.
854 #[no_mangle]
855 pub extern "C" fn WatchedOutput_get_script_pubkey(this_ptr: &WatchedOutput) -> crate::c_types::u8slice {
856         let mut inner_val = &mut this_ptr.get_native_mut_ref().script_pubkey;
857         crate::c_types::u8slice::from_slice(&inner_val[..])
858 }
859 /// Spending condition of the transaction output.
860 #[no_mangle]
861 pub extern "C" fn WatchedOutput_set_script_pubkey(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::CVec_u8Z) {
862         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.script_pubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust());
863 }
864 /// Constructs a new WatchedOutput given each field
865 #[must_use]
866 #[no_mangle]
867 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 {
868         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() }) };
869         WatchedOutput { inner: ObjOps::heap_alloc(nativeWatchedOutput {
870                 block_hash: local_block_hash_arg,
871                 outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
872                 script_pubkey: ::bitcoin::blockdata::script::Script::from(script_pubkey_arg.into_rust()),
873         }), is_owned: true }
874 }
875 impl Clone for WatchedOutput {
876         fn clone(&self) -> Self {
877                 Self {
878                         inner: if <*mut nativeWatchedOutput>::is_null(self.inner) { core::ptr::null_mut() } else {
879                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
880                         is_owned: true,
881                 }
882         }
883 }
884 #[allow(unused)]
885 /// Used only if an object of this type is returned as a trait impl by a method
886 pub(crate) extern "C" fn WatchedOutput_clone_void(this_ptr: *const c_void) -> *mut c_void {
887         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeWatchedOutput)).clone() })) as *mut c_void
888 }
889 #[no_mangle]
890 /// Creates a copy of the WatchedOutput
891 pub extern "C" fn WatchedOutput_clone(orig: &WatchedOutput) -> WatchedOutput {
892         orig.clone()
893 }
894 /// Checks if two WatchedOutputs contain equal inner contents.
895 #[no_mangle]
896 pub extern "C" fn WatchedOutput_hash(o: &WatchedOutput) -> u64 {
897         if o.inner.is_null() { return 0; }
898         // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
899         #[allow(deprecated)]
900         let mut hasher = core::hash::SipHasher::new();
901         core::hash::Hash::hash(o.get_native_ref(), &mut hasher);
902         core::hash::Hasher::finish(&hasher)
903 }