Update auto-generated bindings
[ldk-c-bindings] / lightning-c-bindings / src / lightning / routing / utxo.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 //! This module contains traits for LDK to access UTXOs to check gossip data is correct.
10 //!
11 //! When lightning nodes gossip channel information, they resist DoS attacks by checking that each
12 //! channel matches a UTXO on-chain, requiring at least some marginal on-chain transacting in
13 //! order to announce a channel. This module handles that checking.
14
15 use alloc::str::FromStr;
16 use alloc::string::String;
17 use core::ffi::c_void;
18 use core::convert::Infallible;
19 use bitcoin::hashes::Hash;
20 use crate::c_types::*;
21 #[cfg(feature="no-std")]
22 use alloc::{vec::Vec, boxed::Box};
23
24 /// An error when accessing the chain via [`UtxoLookup`].
25 #[derive(Clone)]
26 #[must_use]
27 #[repr(C)]
28 pub enum UtxoLookupError {
29         /// The requested chain is unknown.
30         UnknownChain,
31         /// The requested transaction doesn't exist or hasn't confirmed.
32         UnknownTx,
33 }
34 use lightning::routing::utxo::UtxoLookupError as UtxoLookupErrorImport;
35 pub(crate) type nativeUtxoLookupError = UtxoLookupErrorImport;
36
37 impl UtxoLookupError {
38         #[allow(unused)]
39         pub(crate) fn to_native(&self) -> nativeUtxoLookupError {
40                 match self {
41                         UtxoLookupError::UnknownChain => nativeUtxoLookupError::UnknownChain,
42                         UtxoLookupError::UnknownTx => nativeUtxoLookupError::UnknownTx,
43                 }
44         }
45         #[allow(unused)]
46         pub(crate) fn into_native(self) -> nativeUtxoLookupError {
47                 match self {
48                         UtxoLookupError::UnknownChain => nativeUtxoLookupError::UnknownChain,
49                         UtxoLookupError::UnknownTx => nativeUtxoLookupError::UnknownTx,
50                 }
51         }
52         #[allow(unused)]
53         pub(crate) fn from_native(native: &nativeUtxoLookupError) -> Self {
54                 match native {
55                         nativeUtxoLookupError::UnknownChain => UtxoLookupError::UnknownChain,
56                         nativeUtxoLookupError::UnknownTx => UtxoLookupError::UnknownTx,
57                 }
58         }
59         #[allow(unused)]
60         pub(crate) fn native_into(native: nativeUtxoLookupError) -> Self {
61                 match native {
62                         nativeUtxoLookupError::UnknownChain => UtxoLookupError::UnknownChain,
63                         nativeUtxoLookupError::UnknownTx => UtxoLookupError::UnknownTx,
64                 }
65         }
66 }
67 /// Creates a copy of the UtxoLookupError
68 #[no_mangle]
69 pub extern "C" fn UtxoLookupError_clone(orig: &UtxoLookupError) -> UtxoLookupError {
70         orig.clone()
71 }
72 #[no_mangle]
73 /// Utility method to constructs a new UnknownChain-variant UtxoLookupError
74 pub extern "C" fn UtxoLookupError_unknown_chain() -> UtxoLookupError {
75         UtxoLookupError::UnknownChain}
76 #[no_mangle]
77 /// Utility method to constructs a new UnknownTx-variant UtxoLookupError
78 pub extern "C" fn UtxoLookupError_unknown_tx() -> UtxoLookupError {
79         UtxoLookupError::UnknownTx}
80 /// The result of a [`UtxoLookup::get_utxo`] call. A call may resolve either synchronously,
81 /// returning the `Sync` variant, or asynchronously, returning an [`UtxoFuture`] in the `Async`
82 /// variant.
83 #[derive(Clone)]
84 #[must_use]
85 #[repr(C)]
86 pub enum UtxoResult {
87         /// A result which was resolved synchronously. It either includes a [`TxOut`] for the output
88         /// requested or a [`UtxoLookupError`].
89         Sync(
90                 crate::c_types::derived::CResult_TxOutUtxoLookupErrorZ),
91         /// A result which will be resolved asynchronously. It includes a [`UtxoFuture`], a `clone` of
92         /// which you must keep locally and call [`UtxoFuture::resolve`] on once the lookup completes.
93         ///
94         /// Note that in order to avoid runaway memory usage, the number of parallel checks is limited,
95         /// but only fairly loosely. Because a pending checks block all message processing, leaving
96         /// checks pending for an extended time may cause DoS of other functions. It is recommended you
97         /// keep a tight timeout on lookups, on the order of a few seconds.
98         Async(
99                 crate::lightning::routing::utxo::UtxoFuture),
100 }
101 use lightning::routing::utxo::UtxoResult as UtxoResultImport;
102 pub(crate) type nativeUtxoResult = UtxoResultImport;
103
104 impl UtxoResult {
105         #[allow(unused)]
106         pub(crate) fn to_native(&self) -> nativeUtxoResult {
107                 match self {
108                         UtxoResult::Sync (ref a, ) => {
109                                 let mut a_nonref = Clone::clone(a);
110                                 let mut local_a_nonref = match a_nonref.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut a_nonref.contents.result)) }).into_rust() }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut a_nonref.contents.err)) }).into_native() })};
111                                 nativeUtxoResult::Sync (
112                                         local_a_nonref,
113                                 )
114                         },
115                         UtxoResult::Async (ref a, ) => {
116                                 let mut a_nonref = Clone::clone(a);
117                                 nativeUtxoResult::Async (
118                                         *unsafe { Box::from_raw(a_nonref.take_inner()) },
119                                 )
120                         },
121                 }
122         }
123         #[allow(unused)]
124         pub(crate) fn into_native(self) -> nativeUtxoResult {
125                 match self {
126                         UtxoResult::Sync (mut a, ) => {
127                                 let mut local_a = match a.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut a.contents.result)) }).into_rust() }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut a.contents.err)) }).into_native() })};
128                                 nativeUtxoResult::Sync (
129                                         local_a,
130                                 )
131                         },
132                         UtxoResult::Async (mut a, ) => {
133                                 nativeUtxoResult::Async (
134                                         *unsafe { Box::from_raw(a.take_inner()) },
135                                 )
136                         },
137                 }
138         }
139         #[allow(unused)]
140         pub(crate) fn from_native(native: &nativeUtxoResult) -> Self {
141                 match native {
142                         nativeUtxoResult::Sync (ref a, ) => {
143                                 let mut a_nonref = Clone::clone(a);
144                                 let mut local_a_nonref = match a_nonref { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::TxOut::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::routing::utxo::UtxoLookupError::native_into(e) }).into() };
145                                 UtxoResult::Sync (
146                                         local_a_nonref,
147                                 )
148                         },
149                         nativeUtxoResult::Async (ref a, ) => {
150                                 let mut a_nonref = Clone::clone(a);
151                                 UtxoResult::Async (
152                                         crate::lightning::routing::utxo::UtxoFuture { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
153                                 )
154                         },
155                 }
156         }
157         #[allow(unused)]
158         pub(crate) fn native_into(native: nativeUtxoResult) -> Self {
159                 match native {
160                         nativeUtxoResult::Sync (mut a, ) => {
161                                 let mut local_a = match a { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::TxOut::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::routing::utxo::UtxoLookupError::native_into(e) }).into() };
162                                 UtxoResult::Sync (
163                                         local_a,
164                                 )
165                         },
166                         nativeUtxoResult::Async (mut a, ) => {
167                                 UtxoResult::Async (
168                                         crate::lightning::routing::utxo::UtxoFuture { inner: ObjOps::heap_alloc(a), is_owned: true },
169                                 )
170                         },
171                 }
172         }
173 }
174 /// Frees any resources used by the UtxoResult
175 #[no_mangle]
176 pub extern "C" fn UtxoResult_free(this_ptr: UtxoResult) { }
177 /// Creates a copy of the UtxoResult
178 #[no_mangle]
179 pub extern "C" fn UtxoResult_clone(orig: &UtxoResult) -> UtxoResult {
180         orig.clone()
181 }
182 #[no_mangle]
183 /// Utility method to constructs a new Sync-variant UtxoResult
184 pub extern "C" fn UtxoResult_sync(a: crate::c_types::derived::CResult_TxOutUtxoLookupErrorZ) -> UtxoResult {
185         UtxoResult::Sync(a, )
186 }
187 #[no_mangle]
188 /// Utility method to constructs a new Async-variant UtxoResult
189 pub extern "C" fn UtxoResult_async(a: crate::lightning::routing::utxo::UtxoFuture) -> UtxoResult {
190         UtxoResult::Async(a, )
191 }
192 /// The `UtxoLookup` trait defines behavior for accessing on-chain UTXOs.
193 #[repr(C)]
194 pub struct UtxoLookup {
195         /// An opaque pointer which is passed to your function implementations as an argument.
196         /// This has no meaning in the LDK, and can be NULL or any other value.
197         pub this_arg: *mut c_void,
198         /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
199         /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
200         /// is unknown.
201         ///
202         /// [`short_channel_id`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#definition-of-short_channel_id
203         pub get_utxo: extern "C" fn (this_arg: *const c_void, genesis_hash: *const [u8; 32], short_channel_id: u64) -> crate::lightning::routing::utxo::UtxoResult,
204         /// Frees any resources associated with this object given its this_arg pointer.
205         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
206         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
207 }
208 unsafe impl Send for UtxoLookup {}
209 unsafe impl Sync for UtxoLookup {}
210 pub(crate) fn UtxoLookup_clone_fields(orig: &UtxoLookup) -> UtxoLookup {
211         UtxoLookup {
212                 this_arg: orig.this_arg,
213                 get_utxo: Clone::clone(&orig.get_utxo),
214                 free: Clone::clone(&orig.free),
215         }
216 }
217
218 use lightning::routing::utxo::UtxoLookup as rustUtxoLookup;
219 impl rustUtxoLookup for UtxoLookup {
220         fn get_utxo(&self, mut genesis_hash: &bitcoin::BlockHash, mut short_channel_id: u64) -> lightning::routing::utxo::UtxoResult {
221                 let mut ret = (self.get_utxo)(self.this_arg, genesis_hash.as_inner(), short_channel_id);
222                 ret.into_native()
223         }
224 }
225
226 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
227 // directly as a Deref trait in higher-level structs:
228 impl core::ops::Deref for UtxoLookup {
229         type Target = Self;
230         fn deref(&self) -> &Self {
231                 self
232         }
233 }
234 impl core::ops::DerefMut for UtxoLookup {
235         fn deref_mut(&mut self) -> &mut Self {
236                 self
237         }
238 }
239 /// Calls the free function if one is set
240 #[no_mangle]
241 pub extern "C" fn UtxoLookup_free(this_ptr: UtxoLookup) { }
242 impl Drop for UtxoLookup {
243         fn drop(&mut self) {
244                 if let Some(f) = self.free {
245                         f(self.this_arg);
246                 }
247         }
248 }
249
250 use lightning::routing::utxo::UtxoFuture as nativeUtxoFutureImport;
251 pub(crate) type nativeUtxoFuture = nativeUtxoFutureImport;
252
253 /// Represents a future resolution of a [`UtxoLookup::get_utxo`] query resolving async.
254 ///
255 /// See [`UtxoResult::Async`] and [`UtxoFuture::resolve`] for more info.
256 #[must_use]
257 #[repr(C)]
258 pub struct UtxoFuture {
259         /// A pointer to the opaque Rust object.
260
261         /// Nearly everywhere, inner must be non-null, however in places where
262         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
263         pub inner: *mut nativeUtxoFuture,
264         /// Indicates that this is the only struct which contains the same pointer.
265
266         /// Rust functions which take ownership of an object provided via an argument require
267         /// this to be true and invalidate the object pointed to by inner.
268         pub is_owned: bool,
269 }
270
271 impl Drop for UtxoFuture {
272         fn drop(&mut self) {
273                 if self.is_owned && !<*mut nativeUtxoFuture>::is_null(self.inner) {
274                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
275                 }
276         }
277 }
278 /// Frees any resources used by the UtxoFuture, if is_owned is set and inner is non-NULL.
279 #[no_mangle]
280 pub extern "C" fn UtxoFuture_free(this_obj: UtxoFuture) { }
281 #[allow(unused)]
282 /// Used only if an object of this type is returned as a trait impl by a method
283 pub(crate) extern "C" fn UtxoFuture_free_void(this_ptr: *mut c_void) {
284         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeUtxoFuture) };
285 }
286 #[allow(unused)]
287 impl UtxoFuture {
288         pub(crate) fn get_native_ref(&self) -> &'static nativeUtxoFuture {
289                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
290         }
291         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeUtxoFuture {
292                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
293         }
294         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
295         pub(crate) fn take_inner(mut self) -> *mut nativeUtxoFuture {
296                 assert!(self.is_owned);
297                 let ret = ObjOps::untweak_ptr(self.inner);
298                 self.inner = core::ptr::null_mut();
299                 ret
300         }
301 }
302 impl Clone for UtxoFuture {
303         fn clone(&self) -> Self {
304                 Self {
305                         inner: if <*mut nativeUtxoFuture>::is_null(self.inner) { core::ptr::null_mut() } else {
306                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
307                         is_owned: true,
308                 }
309         }
310 }
311 #[allow(unused)]
312 /// Used only if an object of this type is returned as a trait impl by a method
313 pub(crate) extern "C" fn UtxoFuture_clone_void(this_ptr: *const c_void) -> *mut c_void {
314         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUtxoFuture)).clone() })) as *mut c_void
315 }
316 #[no_mangle]
317 /// Creates a copy of the UtxoFuture
318 pub extern "C" fn UtxoFuture_clone(orig: &UtxoFuture) -> UtxoFuture {
319         orig.clone()
320 }
321 /// Builds a new future for later resolution.
322 #[must_use]
323 #[no_mangle]
324 pub extern "C" fn UtxoFuture_new() -> crate::lightning::routing::utxo::UtxoFuture {
325         let mut ret = lightning::routing::utxo::UtxoFuture::new();
326         crate::lightning::routing::utxo::UtxoFuture { inner: ObjOps::heap_alloc(ret), is_owned: true }
327 }
328
329 /// Resolves this future against the given `graph` and with the given `result`.
330 ///
331 /// This is identical to calling [`UtxoFuture::resolve`] with a dummy `gossip`, disabling
332 /// forwarding the validated gossip message onwards to peers.
333 ///
334 /// Because this may cause the [`NetworkGraph`]'s [`processing_queue_high`] to flip, in order
335 /// to allow us to interact with peers again, you should call [`PeerManager::process_events`]
336 /// after this.
337 ///
338 /// [`processing_queue_high`]: crate::ln::msgs::RoutingMessageHandler::processing_queue_high
339 /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
340 #[no_mangle]
341 pub extern "C" fn UtxoFuture_resolve_without_forwarding(this_arg: &crate::lightning::routing::utxo::UtxoFuture, graph: &crate::lightning::routing::gossip::NetworkGraph, mut result: crate::c_types::derived::CResult_TxOutUtxoLookupErrorZ) {
342         let mut local_result = match result.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut result.contents.result)) }).into_rust() }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut result.contents.err)) }).into_native() })};
343         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.resolve_without_forwarding(graph.get_native_ref(), local_result)
344 }
345
346 /// Resolves this future against the given `graph` and with the given `result`.
347 ///
348 /// The given `gossip` is used to broadcast any validated messages onwards to all peers which
349 /// have available buffer space.
350 ///
351 /// Because this may cause the [`NetworkGraph`]'s [`processing_queue_high`] to flip, in order
352 /// to allow us to interact with peers again, you should call [`PeerManager::process_events`]
353 /// after this.
354 ///
355 /// [`processing_queue_high`]: crate::ln::msgs::RoutingMessageHandler::processing_queue_high
356 /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
357 #[no_mangle]
358 pub extern "C" fn UtxoFuture_resolve(this_arg: &crate::lightning::routing::utxo::UtxoFuture, graph: &crate::lightning::routing::gossip::NetworkGraph, gossip: &crate::lightning::routing::gossip::P2PGossipSync, mut result: crate::c_types::derived::CResult_TxOutUtxoLookupErrorZ) {
359         let mut local_result = match result.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut result.contents.result)) }).into_rust() }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut result.contents.err)) }).into_native() })};
360         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.resolve(graph.get_native_ref(), gossip.get_native_ref(), local_result)
361 }
362