Rebuild against current RL main
[ldk-c-bindings] / lightning-c-bindings / src / chain / mod.rs
1 //! Structs and traits which allow other parts of rust-lightning to interact with the blockchain.
2
3 use std::ffi::c_void;
4 use bitcoin::hashes::Hash;
5 use crate::c_types::*;
6
7 pub mod chaininterface;
8 pub mod chainmonitor;
9 pub mod channelmonitor;
10 pub mod transaction;
11 pub mod keysinterface;
12 /// An error when accessing the chain via [`Access`].
13 ///
14 /// [`Access`]: trait.Access.html
15 #[must_use]
16 #[derive(Clone)]
17 #[repr(C)]
18 pub enum AccessError {
19         /// The requested chain is unknown.
20         UnknownChain,
21         /// The requested transaction doesn't exist or hasn't confirmed.
22         UnknownTx,
23 }
24 use lightning::chain::AccessError as nativeAccessError;
25 impl AccessError {
26         #[allow(unused)]
27         pub(crate) fn to_native(&self) -> nativeAccessError {
28                 match self {
29                         AccessError::UnknownChain => nativeAccessError::UnknownChain,
30                         AccessError::UnknownTx => nativeAccessError::UnknownTx,
31                 }
32         }
33         #[allow(unused)]
34         pub(crate) fn into_native(self) -> nativeAccessError {
35                 match self {
36                         AccessError::UnknownChain => nativeAccessError::UnknownChain,
37                         AccessError::UnknownTx => nativeAccessError::UnknownTx,
38                 }
39         }
40         #[allow(unused)]
41         pub(crate) fn from_native(native: &nativeAccessError) -> Self {
42                 match native {
43                         nativeAccessError::UnknownChain => AccessError::UnknownChain,
44                         nativeAccessError::UnknownTx => AccessError::UnknownTx,
45                 }
46         }
47         #[allow(unused)]
48         pub(crate) fn native_into(native: nativeAccessError) -> Self {
49                 match native {
50                         nativeAccessError::UnknownChain => AccessError::UnknownChain,
51                         nativeAccessError::UnknownTx => AccessError::UnknownTx,
52                 }
53         }
54 }
55 /// Creates a copy of the AccessError
56 #[no_mangle]
57 pub extern "C" fn AccessError_clone(orig: &AccessError) -> AccessError {
58         orig.clone()
59 }
60 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
61 /// UTXOs.
62 #[repr(C)]
63 pub struct Access {
64         /// An opaque pointer which is passed to your function implementations as an argument.
65         /// This has no meaning in the LDK, and can be NULL or any other value.
66         pub this_arg: *mut c_void,
67         /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
68         /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
69         /// is unknown.
70         ///
71         /// [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
72         #[must_use]
73         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,
74 /// Frees any resources associated with this object given its this_arg pointer.
75 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
76         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
77 }
78 unsafe impl Send for Access {}
79 unsafe impl Sync for Access {}
80
81 use lightning::chain::Access as rustAccess;
82 impl rustAccess for Access {
83         fn get_utxo(&self, genesis_hash: &bitcoin::hash_types::BlockHash, short_channel_id: u64) -> Result<bitcoin::blockdata::transaction::TxOut, lightning::chain::AccessError> {
84                 let mut ret = (self.get_utxo)(self.this_arg, genesis_hash.as_inner(), short_channel_id);
85                 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() })};
86                 local_ret
87         }
88 }
89
90 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
91 // directly as a Deref trait in higher-level structs:
92 impl std::ops::Deref for Access {
93         type Target = Self;
94         fn deref(&self) -> &Self {
95                 self
96         }
97 }
98 /// Calls the free function if one is set
99 #[no_mangle]
100 pub extern "C" fn Access_free(this_ptr: Access) { }
101 impl Drop for Access {
102         fn drop(&mut self) {
103                 if let Some(f) = self.free {
104                         f(self.this_arg);
105                 }
106         }
107 }
108 /// The `Listen` trait is used to be notified of when blocks have been connected or disconnected
109 /// from the chain.
110 ///
111 /// Useful when needing to replay chain data upon startup or as new chain events occur.
112 #[repr(C)]
113 pub struct Listen {
114         /// An opaque pointer which is passed to your function implementations as an argument.
115         /// This has no meaning in the LDK, and can be NULL or any other value.
116         pub this_arg: *mut c_void,
117         /// Notifies the listener that a block was added at the given height.
118         pub block_connected: extern "C" fn (this_arg: *const c_void, block: crate::c_types::u8slice, height: u32),
119         /// Notifies the listener that a block was removed at the given height.
120         pub block_disconnected: extern "C" fn (this_arg: *const c_void, header: *const [u8; 80], height: u32),
121 /// Frees any resources associated with this object given its this_arg pointer.
122 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
123         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
124 }
125
126 use lightning::chain::Listen as rustListen;
127 impl rustListen for Listen {
128         fn block_connected(&self, block: &bitcoin::blockdata::block::Block, height: u32) {
129                 let mut local_block = ::bitcoin::consensus::encode::serialize(block);
130                 (self.block_connected)(self.this_arg, crate::c_types::u8slice::from_slice(&local_block), height)
131         }
132         fn block_disconnected(&self, header: &bitcoin::blockdata::block::BlockHeader, height: u32) {
133                 let mut local_header = { let mut s = [0u8; 80]; s[..].copy_from_slice(&::bitcoin::consensus::encode::serialize(header)); s };
134                 (self.block_disconnected)(self.this_arg, &local_header, height)
135         }
136 }
137
138 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
139 // directly as a Deref trait in higher-level structs:
140 impl std::ops::Deref for Listen {
141         type Target = Self;
142         fn deref(&self) -> &Self {
143                 self
144         }
145 }
146 /// Calls the free function if one is set
147 #[no_mangle]
148 pub extern "C" fn Listen_free(this_ptr: Listen) { }
149 impl Drop for Listen {
150         fn drop(&mut self) {
151                 if let Some(f) = self.free {
152                         f(self.this_arg);
153                 }
154         }
155 }
156 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
157 /// blocks are connected and disconnected.
158 ///
159 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
160 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
161 /// channel state changes and HTLCs are resolved. See method documentation for specific
162 /// requirements.
163 ///
164 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
165 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
166 /// without taking any further action such as persisting the current state.
167 ///
168 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
169 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
170 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
171 /// funds in the channel. See [`ChannelMonitorUpdateErr`] for more details about how to handle
172 /// multiple instances.
173 ///
174 /// [`ChannelMonitor`]: channelmonitor/struct.ChannelMonitor.html
175 /// [`ChannelMonitorUpdateErr`]: channelmonitor/enum.ChannelMonitorUpdateErr.html
176 /// [`PermanentFailure`]: channelmonitor/enum.ChannelMonitorUpdateErr.html#variant.PermanentFailure
177 #[repr(C)]
178 pub struct Watch {
179         /// An opaque pointer which is passed to your function implementations as an argument.
180         /// This has no meaning in the LDK, and can be NULL or any other value.
181         pub this_arg: *mut c_void,
182         /// Watches a channel identified by `funding_txo` using `monitor`.
183         ///
184         /// Implementations are responsible for watching the chain for the funding transaction along
185         /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
186         /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
187         ///
188         /// [`get_outputs_to_watch`]: channelmonitor/struct.ChannelMonitor.html#method.get_outputs_to_watch
189         /// [`block_connected`]: channelmonitor/struct.ChannelMonitor.html#method.block_connected
190         /// [`block_disconnected`]: channelmonitor/struct.ChannelMonitor.html#method.block_disconnected
191         #[must_use]
192         pub watch_channel: extern "C" fn (this_arg: *const c_void, funding_txo: crate::chain::transaction::OutPoint, monitor: crate::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ,
193         /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
194         ///
195         /// Implementations must call [`update_monitor`] with the given update. See
196         /// [`ChannelMonitorUpdateErr`] for invariants around returning an error.
197         ///
198         /// [`update_monitor`]: channelmonitor/struct.ChannelMonitor.html#method.update_monitor
199         /// [`ChannelMonitorUpdateErr`]: channelmonitor/enum.ChannelMonitorUpdateErr.html
200         #[must_use]
201         pub update_channel: extern "C" fn (this_arg: *const c_void, funding_txo: crate::chain::transaction::OutPoint, update: crate::chain::channelmonitor::ChannelMonitorUpdate) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ,
202         /// Returns any monitor events since the last call. Subsequent calls must only return new
203         /// events.
204         #[must_use]
205         pub release_pending_monitor_events: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_MonitorEventZ,
206 /// Frees any resources associated with this object given its this_arg pointer.
207 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
208         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
209 }
210 unsafe impl Send for Watch {}
211 unsafe impl Sync for Watch {}
212
213 use lightning::chain::Watch as rustWatch;
214 impl rustWatch<crate::chain::keysinterface::Sign> for Watch {
215         fn watch_channel(&self, funding_txo: lightning::chain::transaction::OutPoint, monitor: lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
216                 let mut ret = (self.watch_channel)(self.this_arg, crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(funding_txo)), is_owned: true }, crate::chain::channelmonitor::ChannelMonitor { inner: Box::into_raw(Box::new(monitor)), is_owned: true });
217                 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() })};
218                 local_ret
219         }
220         fn update_channel(&self, funding_txo: lightning::chain::transaction::OutPoint, update: lightning::chain::channelmonitor::ChannelMonitorUpdate) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
221                 let mut ret = (self.update_channel)(self.this_arg, crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(funding_txo)), is_owned: true }, crate::chain::channelmonitor::ChannelMonitorUpdate { inner: Box::into_raw(Box::new(update)), is_owned: true });
222                 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() })};
223                 local_ret
224         }
225         fn release_pending_monitor_events(&self) -> Vec<lightning::chain::channelmonitor::MonitorEvent> {
226                 let mut ret = (self.release_pending_monitor_events)(self.this_arg);
227                 let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { item.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 Watch {
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 Watch_free(this_ptr: Watch) { }
243 impl Drop for Watch {
244         fn drop(&mut self) {
245                 if let Some(f) = self.free {
246                         f(self.this_arg);
247                 }
248         }
249 }
250 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
251 /// channels.
252 ///
253 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
254 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
255 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
256 /// receiving full blocks from a chain source, any further filtering is unnecessary.
257 ///
258 /// After an output has been registered, subsequent block retrievals from the chain source must not
259 /// exclude any transactions matching the new criteria nor any in-block descendants of such
260 /// transactions.
261 ///
262 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
263 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
264 /// processed later. Then, in order to block until the data has been processed, any `Watch`
265 /// invocation that has called the `Filter` must return [`TemporaryFailure`].
266 ///
267 /// [`Watch`]: trait.Watch.html
268 /// [`TemporaryFailure`]: channelmonitor/enum.ChannelMonitorUpdateErr.html#variant.TemporaryFailure
269 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
270 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
271 #[repr(C)]
272 pub struct Filter {
273         /// An opaque pointer which is passed to your function implementations as an argument.
274         /// This has no meaning in the LDK, and can be NULL or any other value.
275         pub this_arg: *mut c_void,
276         /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
277         /// a spending condition.
278         pub register_tx: extern "C" fn (this_arg: *const c_void, txid: *const [u8; 32], script_pubkey: crate::c_types::u8slice),
279         /// Registers interest in spends of a transaction output identified by `outpoint` having
280         /// `script_pubkey` as the spending condition.
281         pub register_output: extern "C" fn (this_arg: *const c_void, outpoint: &crate::chain::transaction::OutPoint, script_pubkey: crate::c_types::u8slice),
282 /// Frees any resources associated with this object given its this_arg pointer.
283 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
284         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
285 }
286 unsafe impl Send for Filter {}
287 unsafe impl Sync for Filter {}
288
289 use lightning::chain::Filter as rustFilter;
290 impl rustFilter for Filter {
291         fn register_tx(&self, txid: &bitcoin::hash_types::Txid, script_pubkey: &bitcoin::blockdata::script::Script) {
292                 (self.register_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pubkey[..]))
293         }
294         fn register_output(&self, outpoint: &lightning::chain::transaction::OutPoint, script_pubkey: &bitcoin::blockdata::script::Script) {
295                 (self.register_output)(self.this_arg, &crate::chain::transaction::OutPoint { inner: unsafe { (outpoint as *const _) as *mut _ }, is_owned: false }, crate::c_types::u8slice::from_slice(&script_pubkey[..]))
296         }
297 }
298
299 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
300 // directly as a Deref trait in higher-level structs:
301 impl std::ops::Deref for Filter {
302         type Target = Self;
303         fn deref(&self) -> &Self {
304                 self
305         }
306 }
307 /// Calls the free function if one is set
308 #[no_mangle]
309 pub extern "C" fn Filter_free(this_ptr: Filter) { }
310 impl Drop for Filter {
311         fn drop(&mut self) {
312                 if let Some(f) = self.free {
313                         f(self.this_arg);
314                 }
315         }
316 }