Update auto-generated bindings with new module structure
[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::ffi::c_void;
12 use bitcoin::hashes::Hash;
13 use crate::c_types::*;
14
15 pub mod chaininterface;
16 pub mod chainmonitor;
17 pub mod channelmonitor;
18 pub mod transaction;
19 pub mod keysinterface;
20 /// An error when accessing the chain via [`Access`].
21 #[must_use]
22 #[derive(Clone)]
23 #[repr(C)]
24 pub enum AccessError {
25         /// The requested chain is unknown.
26         UnknownChain,
27         /// The requested transaction doesn't exist or hasn't confirmed.
28         UnknownTx,
29 }
30 use lightning::chain::AccessError as nativeAccessError;
31 impl AccessError {
32         #[allow(unused)]
33         pub(crate) fn to_native(&self) -> nativeAccessError {
34                 match self {
35                         AccessError::UnknownChain => nativeAccessError::UnknownChain,
36                         AccessError::UnknownTx => nativeAccessError::UnknownTx,
37                 }
38         }
39         #[allow(unused)]
40         pub(crate) fn into_native(self) -> nativeAccessError {
41                 match self {
42                         AccessError::UnknownChain => nativeAccessError::UnknownChain,
43                         AccessError::UnknownTx => nativeAccessError::UnknownTx,
44                 }
45         }
46         #[allow(unused)]
47         pub(crate) fn from_native(native: &nativeAccessError) -> Self {
48                 match native {
49                         nativeAccessError::UnknownChain => AccessError::UnknownChain,
50                         nativeAccessError::UnknownTx => AccessError::UnknownTx,
51                 }
52         }
53         #[allow(unused)]
54         pub(crate) fn native_into(native: nativeAccessError) -> Self {
55                 match native {
56                         nativeAccessError::UnknownChain => AccessError::UnknownChain,
57                         nativeAccessError::UnknownTx => AccessError::UnknownTx,
58                 }
59         }
60 }
61 /// Creates a copy of the AccessError
62 #[no_mangle]
63 pub extern "C" fn AccessError_clone(orig: &AccessError) -> AccessError {
64         orig.clone()
65 }
66 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
67 /// UTXOs.
68 #[repr(C)]
69 pub struct Access {
70         /// An opaque pointer which is passed to your function implementations as an argument.
71         /// This has no meaning in the LDK, and can be NULL or any other value.
72         pub this_arg: *mut c_void,
73         /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
74         /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
75         /// is unknown.
76         ///
77         /// [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
78         #[must_use]
79         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,
80         /// Frees any resources associated with this object given its this_arg pointer.
81         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
82         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
83 }
84 unsafe impl Send for Access {}
85 unsafe impl Sync for Access {}
86
87 use lightning::chain::Access as rustAccess;
88 impl rustAccess for Access {
89         fn get_utxo(&self, genesis_hash: &bitcoin::hash_types::BlockHash, short_channel_id: u64) -> Result<bitcoin::blockdata::transaction::TxOut, lightning::chain::AccessError> {
90                 let mut ret = (self.get_utxo)(self.this_arg, genesis_hash.as_inner(), short_channel_id);
91                 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() })};
92                 local_ret
93         }
94 }
95
96 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
97 // directly as a Deref trait in higher-level structs:
98 impl std::ops::Deref for Access {
99         type Target = Self;
100         fn deref(&self) -> &Self {
101                 self
102         }
103 }
104 /// Calls the free function if one is set
105 #[no_mangle]
106 pub extern "C" fn Access_free(this_ptr: Access) { }
107 impl Drop for Access {
108         fn drop(&mut self) {
109                 if let Some(f) = self.free {
110                         f(self.this_arg);
111                 }
112         }
113 }
114 /// The `Listen` trait is used to be notified of when blocks have been connected or disconnected
115 /// from the chain.
116 ///
117 /// Useful when needing to replay chain data upon startup or as new chain events occur.
118 #[repr(C)]
119 pub struct Listen {
120         /// An opaque pointer which is passed to your function implementations as an argument.
121         /// This has no meaning in the LDK, and can be NULL or any other value.
122         pub this_arg: *mut c_void,
123         /// Notifies the listener that a block was added at the given height.
124         pub block_connected: extern "C" fn (this_arg: *const c_void, block: crate::c_types::u8slice, height: u32),
125         /// Notifies the listener that a block was removed at the given height.
126         pub block_disconnected: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
127         /// Frees any resources associated with this object given its this_arg pointer.
128         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
129         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
130 }
131
132 use lightning::chain::Listen as rustListen;
133 impl rustListen for Listen {
134         fn block_connected(&self, block: &bitcoin::blockdata::block::Block, height: u32) {
135                 let mut local_block = ::bitcoin::consensus::encode::serialize(block);
136                 (self.block_connected)(self.this_arg, crate::c_types::u8slice::from_slice(&local_block), height)
137         }
138         fn block_disconnected(&self, header: &bitcoin::blockdata::block::BlockHeader, height: u32) {
139                 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
140                 (self.block_disconnected)(self.this_arg, &local_header, height)
141         }
142 }
143
144 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
145 // directly as a Deref trait in higher-level structs:
146 impl std::ops::Deref for Listen {
147         type Target = Self;
148         fn deref(&self) -> &Self {
149                 self
150         }
151 }
152 /// Calls the free function if one is set
153 #[no_mangle]
154 pub extern "C" fn Listen_free(this_ptr: Listen) { }
155 impl Drop for Listen {
156         fn drop(&mut self) {
157                 if let Some(f) = self.free {
158                         f(self.this_arg);
159                 }
160         }
161 }
162 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
163 /// blocks are connected and disconnected.
164 ///
165 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
166 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
167 /// channel state changes and HTLCs are resolved. See method documentation for specific
168 /// requirements.
169 ///
170 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
171 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
172 /// without taking any further action such as persisting the current state.
173 ///
174 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
175 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
176 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
177 /// funds in the channel. See [`ChannelMonitorUpdateErr`] for more details about how to handle
178 /// multiple instances.
179 ///
180 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
181 /// [`ChannelMonitorUpdateErr`]: channelmonitor::ChannelMonitorUpdateErr
182 /// [`PermanentFailure`]: channelmonitor::ChannelMonitorUpdateErr::PermanentFailure
183 #[repr(C)]
184 pub struct Watch {
185         /// An opaque pointer which is passed to your function implementations as an argument.
186         /// This has no meaning in the LDK, and can be NULL or any other value.
187         pub this_arg: *mut c_void,
188         /// Watches a channel identified by `funding_txo` using `monitor`.
189         ///
190         /// Implementations are responsible for watching the chain for the funding transaction along
191         /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
192         /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
193         ///
194         /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
195         /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
196         /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
197         #[must_use]
198         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,
199         /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
200         ///
201         /// Implementations must call [`update_monitor`] with the given update. See
202         /// [`ChannelMonitorUpdateErr`] for invariants around returning an error.
203         ///
204         /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
205         /// [`ChannelMonitorUpdateErr`]: channelmonitor::ChannelMonitorUpdateErr
206         #[must_use]
207         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,
208         /// Returns any monitor events since the last call. Subsequent calls must only return new
209         /// events.
210         #[must_use]
211         pub release_pending_monitor_events: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_MonitorEventZ,
212         /// Frees any resources associated with this object given its this_arg pointer.
213         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
214         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
215 }
216 unsafe impl Send for Watch {}
217 unsafe impl Sync for Watch {}
218
219 use lightning::chain::Watch as rustWatch;
220 impl rustWatch<crate::lightning::chain::keysinterface::Sign> for Watch {
221         fn watch_channel(&self, funding_txo: lightning::chain::transaction::OutPoint, monitor: lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
222                 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 });
223                 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() })};
224                 local_ret
225         }
226         fn update_channel(&self, funding_txo: lightning::chain::transaction::OutPoint, update: lightning::chain::channelmonitor::ChannelMonitorUpdate) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
227                 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 });
228                 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() })};
229                 local_ret
230         }
231         fn release_pending_monitor_events(&self) -> Vec<lightning::chain::channelmonitor::MonitorEvent> {
232                 let mut ret = (self.release_pending_monitor_events)(self.this_arg);
233                 let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { item.into_native() }); };
234                 local_ret
235         }
236 }
237
238 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
239 // directly as a Deref trait in higher-level structs:
240 impl std::ops::Deref for Watch {
241         type Target = Self;
242         fn deref(&self) -> &Self {
243                 self
244         }
245 }
246 /// Calls the free function if one is set
247 #[no_mangle]
248 pub extern "C" fn Watch_free(this_ptr: Watch) { }
249 impl Drop for Watch {
250         fn drop(&mut self) {
251                 if let Some(f) = self.free {
252                         f(self.this_arg);
253                 }
254         }
255 }
256 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
257 /// channels.
258 ///
259 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
260 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
261 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
262 /// receiving full blocks from a chain source, any further filtering is unnecessary.
263 ///
264 /// After an output has been registered, subsequent block retrievals from the chain source must not
265 /// exclude any transactions matching the new criteria nor any in-block descendants of such
266 /// transactions.
267 ///
268 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
269 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
270 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
271 /// invocation that has called the `Filter` must return [`TemporaryFailure`].
272 ///
273 /// [`TemporaryFailure`]: channelmonitor::ChannelMonitorUpdateErr::TemporaryFailure
274 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
275 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
276 #[repr(C)]
277 pub struct Filter {
278         /// An opaque pointer which is passed to your function implementations as an argument.
279         /// This has no meaning in the LDK, and can be NULL or any other value.
280         pub this_arg: *mut c_void,
281         /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
282         /// a spending condition.
283         pub register_tx: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32], script_pubkey: crate::c_types::u8slice),
284         /// Registers interest in spends of a transaction output.
285         ///
286         /// Optionally, when `output.block_hash` is set, should return any transaction spending the
287         /// output that is found in the corresponding block along with its index.
288         ///
289         /// This return value is useful for Electrum clients in order to supply in-block descendant
290         /// transactions which otherwise were not included. This is not necessary for other clients if
291         /// such descendant transactions were already included (e.g., when a BIP 157 client provides the
292         /// full block).
293         #[must_use]
294         pub register_output: extern "C" fn (this_arg: *const c_void, output: crate::lightning::chain::WatchedOutput) -> crate::c_types::derived::COption_C2Tuple_usizeTransactionZZ,
295         /// Frees any resources associated with this object given its this_arg pointer.
296         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
297         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
298 }
299 unsafe impl Send for Filter {}
300 unsafe impl Sync for Filter {}
301
302 use lightning::chain::Filter as rustFilter;
303 impl rustFilter for Filter {
304         fn register_tx(&self, txid: &bitcoin::hash_types::Txid, script_pubkey: &bitcoin::blockdata::script::Script) {
305                 (self.register_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pubkey[..]))
306         }
307         fn register_output(&self, output: lightning::chain::WatchedOutput) -> Option<(usize, bitcoin::blockdata::transaction::Transaction)> {
308                 let mut ret = (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: Box::into_raw(Box::new(output)), is_owned: true });
309                 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 };
310                 local_ret
311         }
312 }
313
314 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
315 // directly as a Deref trait in higher-level structs:
316 impl std::ops::Deref for Filter {
317         type Target = Self;
318         fn deref(&self) -> &Self {
319                 self
320         }
321 }
322 /// Calls the free function if one is set
323 #[no_mangle]
324 pub extern "C" fn Filter_free(this_ptr: Filter) { }
325 impl Drop for Filter {
326         fn drop(&mut self) {
327                 if let Some(f) = self.free {
328                         f(self.this_arg);
329                 }
330         }
331 }
332
333 use lightning::chain::WatchedOutput as nativeWatchedOutputImport;
334 type nativeWatchedOutput = nativeWatchedOutputImport;
335
336 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
337 ///
338 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
339 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
340 /// the return value of [`Filter::register_output`].
341 ///
342 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
343 /// may have been spent there. See [`Filter::register_output`] for details.
344 ///
345 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
346 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
347 #[must_use]
348 #[repr(C)]
349 pub struct WatchedOutput {
350         /// A pointer to the opaque Rust object.
351
352         /// Nearly everywhere, inner must be non-null, however in places where
353         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
354         pub inner: *mut nativeWatchedOutput,
355         /// Indicates that this is the only struct which contains the same pointer.
356
357         /// Rust functions which take ownership of an object provided via an argument require
358         /// this to be true and invalidate the object pointed to by inner.
359         pub is_owned: bool,
360 }
361
362 impl Drop for WatchedOutput {
363         fn drop(&mut self) {
364                 if self.is_owned && !<*mut nativeWatchedOutput>::is_null(self.inner) {
365                         let _ = unsafe { Box::from_raw(self.inner) };
366                 }
367         }
368 }
369 /// Frees any resources used by the WatchedOutput, if is_owned is set and inner is non-NULL.
370 #[no_mangle]
371 pub extern "C" fn WatchedOutput_free(this_obj: WatchedOutput) { }
372 #[allow(unused)]
373 /// Used only if an object of this type is returned as a trait impl by a method
374 extern "C" fn WatchedOutput_free_void(this_ptr: *mut c_void) {
375         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeWatchedOutput); }
376 }
377 #[allow(unused)]
378 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
379 impl WatchedOutput {
380         pub(crate) fn take_inner(mut self) -> *mut nativeWatchedOutput {
381                 assert!(self.is_owned);
382                 let ret = self.inner;
383                 self.inner = std::ptr::null_mut();
384                 ret
385         }
386 }
387 /// First block where the transaction output may have been spent.
388 #[no_mangle]
389 pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crate::c_types::ThirtyTwoBytes {
390         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.block_hash;
391         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() } } };
392         local_inner_val
393 }
394 /// First block where the transaction output may have been spent.
395 #[no_mangle]
396 pub extern "C" fn WatchedOutput_set_block_hash(this_ptr: &mut WatchedOutput, mut val: crate::c_types::ThirtyTwoBytes) {
397         let mut local_val = if val.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap() }) };
398         unsafe { &mut *this_ptr.inner }.block_hash = local_val;
399 }
400 /// Outpoint identifying the transaction output.
401 #[no_mangle]
402 pub extern "C" fn WatchedOutput_get_outpoint(this_ptr: &WatchedOutput) -> crate::lightning::chain::transaction::OutPoint {
403         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.outpoint;
404         crate::lightning::chain::transaction::OutPoint { inner: unsafe { ( (&((*inner_val)) as *const _) as *mut _) }, is_owned: false }
405 }
406 /// Outpoint identifying the transaction output.
407 #[no_mangle]
408 pub extern "C" fn WatchedOutput_set_outpoint(this_ptr: &mut WatchedOutput, mut val: crate::lightning::chain::transaction::OutPoint) {
409         unsafe { &mut *this_ptr.inner }.outpoint = *unsafe { Box::from_raw(val.take_inner()) };
410 }
411 /// Spending condition of the transaction output.
412 #[no_mangle]
413 pub extern "C" fn WatchedOutput_get_script_pubkey(this_ptr: &WatchedOutput) -> crate::c_types::u8slice {
414         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.script_pubkey;
415         crate::c_types::u8slice::from_slice(&(*inner_val)[..])
416 }
417 /// Spending condition of the transaction output.
418 #[no_mangle]
419 pub extern "C" fn WatchedOutput_set_script_pubkey(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::CVec_u8Z) {
420         unsafe { &mut *this_ptr.inner }.script_pubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust());
421 }
422 /// Constructs a new WatchedOutput given each field
423 #[must_use]
424 #[no_mangle]
425 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 {
426         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() }) };
427         WatchedOutput { inner: Box::into_raw(Box::new(nativeWatchedOutput {
428                 block_hash: local_block_hash_arg,
429                 outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) },
430                 script_pubkey: ::bitcoin::blockdata::script::Script::from(script_pubkey_arg.into_rust()),
431         })), is_owned: true }
432 }