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