1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
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.
9 //! Structs and traits which allow other parts of rust-lightning to interact with the blockchain.
12 use bitcoin::hashes::Hash;
13 use crate::c_types::*;
15 pub mod chaininterface;
17 pub mod channelmonitor;
19 pub mod keysinterface;
20 /// An error when accessing the chain via [`Access`].
24 pub enum AccessError {
25 /// The requested chain is unknown.
27 /// The requested transaction doesn't exist or hasn't confirmed.
30 use lightning::chain::AccessError as nativeAccessError;
33 pub(crate) fn to_native(&self) -> nativeAccessError {
35 AccessError::UnknownChain => nativeAccessError::UnknownChain,
36 AccessError::UnknownTx => nativeAccessError::UnknownTx,
40 pub(crate) fn into_native(self) -> nativeAccessError {
42 AccessError::UnknownChain => nativeAccessError::UnknownChain,
43 AccessError::UnknownTx => nativeAccessError::UnknownTx,
47 pub(crate) fn from_native(native: &nativeAccessError) -> Self {
49 nativeAccessError::UnknownChain => AccessError::UnknownChain,
50 nativeAccessError::UnknownTx => AccessError::UnknownTx,
54 pub(crate) fn native_into(native: nativeAccessError) -> Self {
56 nativeAccessError::UnknownChain => AccessError::UnknownChain,
57 nativeAccessError::UnknownTx => AccessError::UnknownTx,
61 /// Creates a copy of the AccessError
63 pub extern "C" fn AccessError_clone(orig: &AccessError) -> AccessError {
66 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
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
77 /// [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
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)>,
84 unsafe impl Send for Access {}
85 unsafe impl Sync for Access {}
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() })};
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 {
100 fn deref(&self) -> &Self {
104 /// Calls the free function if one is set
106 pub extern "C" fn Access_free(this_ptr: Access) { }
107 impl Drop for Access {
109 if let Some(f) = self.free {
114 /// The `Listen` trait is used to be notified of when blocks have been connected or disconnected
117 /// Useful when needing to replay chain data upon startup or as new chain events occur.
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)>,
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)
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)
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 {
148 fn deref(&self) -> &Self {
152 /// Calls the free function if one is set
154 pub extern "C" fn Listen_free(this_ptr: Listen) { }
155 impl Drop for Listen {
157 if let Some(f) = self.free {
162 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
163 /// blocks are connected and disconnected.
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
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.
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.
180 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
181 /// [`ChannelMonitorUpdateErr`]: channelmonitor::ChannelMonitorUpdateErr
182 /// [`PermanentFailure`]: channelmonitor::ChannelMonitorUpdateErr::PermanentFailure
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`.
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.
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
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.
201 /// Implementations must call [`update_monitor`] with the given update. See
202 /// [`ChannelMonitorUpdateErr`] for invariants around returning an error.
204 /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
205 /// [`ChannelMonitorUpdateErr`]: channelmonitor::ChannelMonitorUpdateErr
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
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)>,
216 unsafe impl Send for Watch {}
217 unsafe impl Sync for Watch {}
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() })};
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() })};
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() }); };
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 {
242 fn deref(&self) -> &Self {
246 /// Calls the free function if one is set
248 pub extern "C" fn Watch_free(this_ptr: Watch) { }
249 impl Drop for Watch {
251 if let Some(f) = self.free {
256 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
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.
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
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`].
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
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.
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.
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
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)>,
299 unsafe impl Send for Filter {}
300 unsafe impl Sync for Filter {}
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[..]))
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 };
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 {
318 fn deref(&self) -> &Self {
322 /// Calls the free function if one is set
324 pub extern "C" fn Filter_free(this_ptr: Filter) { }
325 impl Drop for Filter {
327 if let Some(f) = self.free {
333 use lightning::chain::WatchedOutput as nativeWatchedOutputImport;
334 type nativeWatchedOutput = nativeWatchedOutputImport;
336 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
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`].
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.
345 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
346 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
349 pub struct WatchedOutput {
350 /// A pointer to the opaque Rust object.
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.
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.
362 impl Drop for WatchedOutput {
364 if self.is_owned && !<*mut nativeWatchedOutput>::is_null(self.inner) {
365 let _ = unsafe { Box::from_raw(self.inner) };
369 /// Frees any resources used by the WatchedOutput, if is_owned is set and inner is non-NULL.
371 pub extern "C" fn WatchedOutput_free(this_obj: WatchedOutput) { }
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); }
378 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
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();
387 /// First block where the transaction output may have been spent.
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() } } };
394 /// First block where the transaction output may have been spent.
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;
400 /// Outpoint identifying the transaction output.
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 }
406 /// Outpoint identifying the transaction output.
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()) };
411 /// Spending condition of the transaction output.
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)[..])
417 /// Spending condition of the transaction output.
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());
422 /// Constructs a new WatchedOutput given each field
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 }