6ebae6c13c2b7c2eeafe7cc50c2809d4b50ecf53
[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 #[allow(unused)]
73 /// Used only if an object of this type is returned as a trait impl by a method
74 pub(crate) extern "C" fn UtxoLookupError_clone_void(this_ptr: *const c_void) -> *mut c_void {
75         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const UtxoLookupError)).clone() })) as *mut c_void
76 }
77 #[allow(unused)]
78 /// Used only if an object of this type is returned as a trait impl by a method
79 pub(crate) extern "C" fn UtxoLookupError_free_void(this_ptr: *mut c_void) {
80         let _ = unsafe { Box::from_raw(this_ptr as *mut UtxoLookupError) };
81 }
82 #[no_mangle]
83 /// Utility method to constructs a new UnknownChain-variant UtxoLookupError
84 pub extern "C" fn UtxoLookupError_unknown_chain() -> UtxoLookupError {
85         UtxoLookupError::UnknownChain}
86 #[no_mangle]
87 /// Utility method to constructs a new UnknownTx-variant UtxoLookupError
88 pub extern "C" fn UtxoLookupError_unknown_tx() -> UtxoLookupError {
89         UtxoLookupError::UnknownTx}
90 /// The result of a [`UtxoLookup::get_utxo`] call. A call may resolve either synchronously,
91 /// returning the `Sync` variant, or asynchronously, returning an [`UtxoFuture`] in the `Async`
92 /// variant.
93 #[derive(Clone)]
94 #[must_use]
95 #[repr(C)]
96 pub enum UtxoResult {
97         /// A result which was resolved synchronously. It either includes a [`TxOut`] for the output
98         /// requested or a [`UtxoLookupError`].
99         Sync(
100                 crate::c_types::derived::CResult_TxOutUtxoLookupErrorZ),
101         /// A result which will be resolved asynchronously. It includes a [`UtxoFuture`], a `clone` of
102         /// which you must keep locally and call [`UtxoFuture::resolve`] on once the lookup completes.
103         ///
104         /// Note that in order to avoid runaway memory usage, the number of parallel checks is limited,
105         /// but only fairly loosely. Because a pending checks block all message processing, leaving
106         /// checks pending for an extended time may cause DoS of other functions. It is recommended you
107         /// keep a tight timeout on lookups, on the order of a few seconds.
108         Async(
109                 crate::lightning::routing::utxo::UtxoFuture),
110 }
111 use lightning::routing::utxo::UtxoResult as UtxoResultImport;
112 pub(crate) type nativeUtxoResult = UtxoResultImport;
113
114 impl UtxoResult {
115         #[allow(unused)]
116         pub(crate) fn to_native(&self) -> nativeUtxoResult {
117                 match self {
118                         UtxoResult::Sync (ref a, ) => {
119                                 let mut a_nonref = Clone::clone(a);
120                                 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() })};
121                                 nativeUtxoResult::Sync (
122                                         local_a_nonref,
123                                 )
124                         },
125                         UtxoResult::Async (ref a, ) => {
126                                 let mut a_nonref = Clone::clone(a);
127                                 nativeUtxoResult::Async (
128                                         *unsafe { Box::from_raw(a_nonref.take_inner()) },
129                                 )
130                         },
131                 }
132         }
133         #[allow(unused)]
134         pub(crate) fn into_native(self) -> nativeUtxoResult {
135                 match self {
136                         UtxoResult::Sync (mut a, ) => {
137                                 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() })};
138                                 nativeUtxoResult::Sync (
139                                         local_a,
140                                 )
141                         },
142                         UtxoResult::Async (mut a, ) => {
143                                 nativeUtxoResult::Async (
144                                         *unsafe { Box::from_raw(a.take_inner()) },
145                                 )
146                         },
147                 }
148         }
149         #[allow(unused)]
150         pub(crate) fn from_native(native: &nativeUtxoResult) -> Self {
151                 match native {
152                         nativeUtxoResult::Sync (ref a, ) => {
153                                 let mut a_nonref = Clone::clone(a);
154                                 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() };
155                                 UtxoResult::Sync (
156                                         local_a_nonref,
157                                 )
158                         },
159                         nativeUtxoResult::Async (ref a, ) => {
160                                 let mut a_nonref = Clone::clone(a);
161                                 UtxoResult::Async (
162                                         crate::lightning::routing::utxo::UtxoFuture { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
163                                 )
164                         },
165                 }
166         }
167         #[allow(unused)]
168         pub(crate) fn native_into(native: nativeUtxoResult) -> Self {
169                 match native {
170                         nativeUtxoResult::Sync (mut a, ) => {
171                                 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() };
172                                 UtxoResult::Sync (
173                                         local_a,
174                                 )
175                         },
176                         nativeUtxoResult::Async (mut a, ) => {
177                                 UtxoResult::Async (
178                                         crate::lightning::routing::utxo::UtxoFuture { inner: ObjOps::heap_alloc(a), is_owned: true },
179                                 )
180                         },
181                 }
182         }
183 }
184 /// Frees any resources used by the UtxoResult
185 #[no_mangle]
186 pub extern "C" fn UtxoResult_free(this_ptr: UtxoResult) { }
187 /// Creates a copy of the UtxoResult
188 #[no_mangle]
189 pub extern "C" fn UtxoResult_clone(orig: &UtxoResult) -> UtxoResult {
190         orig.clone()
191 }
192 #[allow(unused)]
193 /// Used only if an object of this type is returned as a trait impl by a method
194 pub(crate) extern "C" fn UtxoResult_clone_void(this_ptr: *const c_void) -> *mut c_void {
195         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const UtxoResult)).clone() })) as *mut c_void
196 }
197 #[allow(unused)]
198 /// Used only if an object of this type is returned as a trait impl by a method
199 pub(crate) extern "C" fn UtxoResult_free_void(this_ptr: *mut c_void) {
200         let _ = unsafe { Box::from_raw(this_ptr as *mut UtxoResult) };
201 }
202 #[no_mangle]
203 /// Utility method to constructs a new Sync-variant UtxoResult
204 pub extern "C" fn UtxoResult_sync(a: crate::c_types::derived::CResult_TxOutUtxoLookupErrorZ) -> UtxoResult {
205         UtxoResult::Sync(a, )
206 }
207 #[no_mangle]
208 /// Utility method to constructs a new Async-variant UtxoResult
209 pub extern "C" fn UtxoResult_async(a: crate::lightning::routing::utxo::UtxoFuture) -> UtxoResult {
210         UtxoResult::Async(a, )
211 }
212 /// The `UtxoLookup` trait defines behavior for accessing on-chain UTXOs.
213 #[repr(C)]
214 pub struct UtxoLookup {
215         /// An opaque pointer which is passed to your function implementations as an argument.
216         /// This has no meaning in the LDK, and can be NULL or any other value.
217         pub this_arg: *mut c_void,
218         /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
219         /// Returns an error if `chain_hash` is for a different chain or if such a transaction output is
220         /// unknown.
221         ///
222         /// [`short_channel_id`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#definition-of-short_channel_id
223         pub get_utxo: extern "C" fn (this_arg: *const c_void, chain_hash: *const [u8; 32], short_channel_id: u64) -> crate::lightning::routing::utxo::UtxoResult,
224         /// Frees any resources associated with this object given its this_arg pointer.
225         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
226         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
227 }
228 unsafe impl Send for UtxoLookup {}
229 unsafe impl Sync for UtxoLookup {}
230 #[allow(unused)]
231 pub(crate) fn UtxoLookup_clone_fields(orig: &UtxoLookup) -> UtxoLookup {
232         UtxoLookup {
233                 this_arg: orig.this_arg,
234                 get_utxo: Clone::clone(&orig.get_utxo),
235                 free: Clone::clone(&orig.free),
236         }
237 }
238
239 use lightning::routing::utxo::UtxoLookup as rustUtxoLookup;
240 impl rustUtxoLookup for UtxoLookup {
241         fn get_utxo(&self, mut chain_hash: &bitcoin::blockdata::constants::ChainHash, mut short_channel_id: u64) -> lightning::routing::utxo::UtxoResult {
242                 let mut ret = (self.get_utxo)(self.this_arg, chain_hash.as_bytes(), short_channel_id);
243                 ret.into_native()
244         }
245 }
246
247 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
248 // directly as a Deref trait in higher-level structs:
249 impl core::ops::Deref for UtxoLookup {
250         type Target = Self;
251         fn deref(&self) -> &Self {
252                 self
253         }
254 }
255 impl core::ops::DerefMut for UtxoLookup {
256         fn deref_mut(&mut self) -> &mut Self {
257                 self
258         }
259 }
260 /// Calls the free function if one is set
261 #[no_mangle]
262 pub extern "C" fn UtxoLookup_free(this_ptr: UtxoLookup) { }
263 impl Drop for UtxoLookup {
264         fn drop(&mut self) {
265                 if let Some(f) = self.free {
266                         f(self.this_arg);
267                 }
268         }
269 }
270
271 use lightning::routing::utxo::UtxoFuture as nativeUtxoFutureImport;
272 pub(crate) type nativeUtxoFuture = nativeUtxoFutureImport;
273
274 /// Represents a future resolution of a [`UtxoLookup::get_utxo`] query resolving async.
275 ///
276 /// See [`UtxoResult::Async`] and [`UtxoFuture::resolve`] for more info.
277 #[must_use]
278 #[repr(C)]
279 pub struct UtxoFuture {
280         /// A pointer to the opaque Rust object.
281
282         /// Nearly everywhere, inner must be non-null, however in places where
283         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
284         pub inner: *mut nativeUtxoFuture,
285         /// Indicates that this is the only struct which contains the same pointer.
286
287         /// Rust functions which take ownership of an object provided via an argument require
288         /// this to be true and invalidate the object pointed to by inner.
289         pub is_owned: bool,
290 }
291
292 impl Drop for UtxoFuture {
293         fn drop(&mut self) {
294                 if self.is_owned && !<*mut nativeUtxoFuture>::is_null(self.inner) {
295                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
296                 }
297         }
298 }
299 /// Frees any resources used by the UtxoFuture, if is_owned is set and inner is non-NULL.
300 #[no_mangle]
301 pub extern "C" fn UtxoFuture_free(this_obj: UtxoFuture) { }
302 #[allow(unused)]
303 /// Used only if an object of this type is returned as a trait impl by a method
304 pub(crate) extern "C" fn UtxoFuture_free_void(this_ptr: *mut c_void) {
305         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeUtxoFuture) };
306 }
307 #[allow(unused)]
308 impl UtxoFuture {
309         pub(crate) fn get_native_ref(&self) -> &'static nativeUtxoFuture {
310                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
311         }
312         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeUtxoFuture {
313                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
314         }
315         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
316         pub(crate) fn take_inner(mut self) -> *mut nativeUtxoFuture {
317                 assert!(self.is_owned);
318                 let ret = ObjOps::untweak_ptr(self.inner);
319                 self.inner = core::ptr::null_mut();
320                 ret
321         }
322 }
323 impl Clone for UtxoFuture {
324         fn clone(&self) -> Self {
325                 Self {
326                         inner: if <*mut nativeUtxoFuture>::is_null(self.inner) { core::ptr::null_mut() } else {
327                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
328                         is_owned: true,
329                 }
330         }
331 }
332 #[allow(unused)]
333 /// Used only if an object of this type is returned as a trait impl by a method
334 pub(crate) extern "C" fn UtxoFuture_clone_void(this_ptr: *const c_void) -> *mut c_void {
335         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeUtxoFuture)).clone() })) as *mut c_void
336 }
337 #[no_mangle]
338 /// Creates a copy of the UtxoFuture
339 pub extern "C" fn UtxoFuture_clone(orig: &UtxoFuture) -> UtxoFuture {
340         orig.clone()
341 }
342 /// Builds a new future for later resolution.
343 #[must_use]
344 #[no_mangle]
345 pub extern "C" fn UtxoFuture_new() -> crate::lightning::routing::utxo::UtxoFuture {
346         let mut ret = lightning::routing::utxo::UtxoFuture::new();
347         crate::lightning::routing::utxo::UtxoFuture { inner: ObjOps::heap_alloc(ret), is_owned: true }
348 }
349
350 /// Resolves this future against the given `graph` and with the given `result`.
351 ///
352 /// This is identical to calling [`UtxoFuture::resolve`] with a dummy `gossip`, disabling
353 /// forwarding the validated gossip message onwards to peers.
354 ///
355 /// Because this may cause the [`NetworkGraph`]'s [`processing_queue_high`] to flip, in order
356 /// to allow us to interact with peers again, you should call [`PeerManager::process_events`]
357 /// after this.
358 ///
359 /// [`processing_queue_high`]: crate::ln::msgs::RoutingMessageHandler::processing_queue_high
360 /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
361 #[no_mangle]
362 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) {
363         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() })};
364         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.resolve_without_forwarding(graph.get_native_ref(), local_result)
365 }
366
367 /// Resolves this future against the given `graph` and with the given `result`.
368 ///
369 /// The given `gossip` is used to broadcast any validated messages onwards to all peers which
370 /// have available buffer space.
371 ///
372 /// Because this may cause the [`NetworkGraph`]'s [`processing_queue_high`] to flip, in order
373 /// to allow us to interact with peers again, you should call [`PeerManager::process_events`]
374 /// after this.
375 ///
376 /// [`processing_queue_high`]: crate::ln::msgs::RoutingMessageHandler::processing_queue_high
377 /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
378 #[no_mangle]
379 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) {
380         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() })};
381         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.resolve(graph.get_native_ref(), gossip.get_native_ref(), local_result)
382 }
383