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