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