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