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