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