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