Pin compiler_builtins to 0.1.109 when building std
[ldk-c-bindings] / lightning-c-bindings / src / lightning / chain / chaininterface.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 //! Traits and utility impls which allow other parts of rust-lightning to interact with the
10 //! blockchain.
11 //!
12 //! Includes traits for monitoring and receiving notifications of new blocks and block
13 //! disconnections, transaction broadcasting, and feerate information requests.
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 interface to send a transaction to the Bitcoin network.
25 #[repr(C)]
26 pub struct BroadcasterInterface {
27         /// An opaque pointer which is passed to your function implementations as an argument.
28         /// This has no meaning in the LDK, and can be NULL or any other value.
29         pub this_arg: *mut c_void,
30         /// Sends a list of transactions out to (hopefully) be mined.
31         /// This only needs to handle the actual broadcasting of transactions, LDK will automatically
32         /// rebroadcast transactions that haven't made it into a block.
33         ///
34         /// In some cases LDK may attempt to broadcast a transaction which double-spends another
35         /// and this isn't a bug and can be safely ignored.
36         ///
37         /// If more than one transaction is given, these transactions should be considered to be a
38         /// package and broadcast together. Some of the transactions may or may not depend on each other,
39         /// be sure to manage both cases correctly.
40         ///
41         /// Bitcoin transaction packages are defined in BIP 331 and here:
42         /// <https://github.com/bitcoin/bitcoin/blob/master/doc/policy/packages.md>
43         pub broadcast_transactions: extern "C" fn (this_arg: *const c_void, txs: crate::c_types::derived::CVec_TransactionZ),
44         /// Frees any resources associated with this object given its this_arg pointer.
45         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
46         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
47 }
48 unsafe impl Send for BroadcasterInterface {}
49 unsafe impl Sync for BroadcasterInterface {}
50 #[allow(unused)]
51 pub(crate) fn BroadcasterInterface_clone_fields(orig: &BroadcasterInterface) -> BroadcasterInterface {
52         BroadcasterInterface {
53                 this_arg: orig.this_arg,
54                 broadcast_transactions: Clone::clone(&orig.broadcast_transactions),
55                 free: Clone::clone(&orig.free),
56         }
57 }
58
59 use lightning::chain::chaininterface::BroadcasterInterface as rustBroadcasterInterface;
60 impl rustBroadcasterInterface for BroadcasterInterface {
61         fn broadcast_transactions(&self, mut txs: &[&bitcoin::blockdata::transaction::Transaction]) {
62                 let mut local_txs = Vec::new(); for item in txs.iter() { local_txs.push( { crate::c_types::Transaction::from_bitcoin((*item)) }); };
63                 (self.broadcast_transactions)(self.this_arg, local_txs.into())
64         }
65 }
66
67 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
68 // directly as a Deref trait in higher-level structs:
69 impl core::ops::Deref for BroadcasterInterface {
70         type Target = Self;
71         fn deref(&self) -> &Self {
72                 self
73         }
74 }
75 impl core::ops::DerefMut for BroadcasterInterface {
76         fn deref_mut(&mut self) -> &mut Self {
77                 self
78         }
79 }
80 /// Calls the free function if one is set
81 #[no_mangle]
82 pub extern "C" fn BroadcasterInterface_free(this_ptr: BroadcasterInterface) { }
83 impl Drop for BroadcasterInterface {
84         fn drop(&mut self) {
85                 if let Some(f) = self.free {
86                         f(self.this_arg);
87                 }
88         }
89 }
90 /// An enum that represents the priority at which we want a transaction to confirm used for feerate
91 /// estimation.
92 #[derive(Clone)]
93 #[must_use]
94 #[repr(C)]
95 pub enum ConfirmationTarget {
96         /// We have some funds available on chain which we need to spend prior to some expiry time at
97         /// which point our counterparty may be able to steal them. Generally we have in the high tens
98         /// to low hundreds of blocks to get our transaction on-chain, but we shouldn't risk too low a
99         /// fee - this should be a relatively high priority feerate.
100         OnChainSweep,
101         /// This is the lowest feerate we will allow our channel counterparty to have in an anchor
102         /// channel in order to close the channel if a channel party goes away.
103         ///
104         /// This needs to be sufficient to get into the mempool when the channel needs to
105         /// be force-closed. Setting too high may result in force-closures if our counterparty attempts
106         /// to use a lower feerate. Because this is for anchor channels, we can always bump the feerate
107         /// later; the feerate here only needs to be sufficient to enter the mempool.
108         ///
109         /// A good estimate is the expected mempool minimum at the time of force-closure. Obviously this
110         /// is not an estimate which is very easy to calculate because we do not know the future. Using
111         /// a simple long-term fee estimate or tracking of the mempool minimum is a good approach to
112         /// ensure you can always close the channel. A future change to Bitcoin's P2P network
113         /// (package relay) may obviate the need for this entirely.
114         MinAllowedAnchorChannelRemoteFee,
115         /// The lowest feerate we will allow our channel counterparty to have in a non-anchor channel.
116         ///
117         /// This is the feerate on the transaction which we (or our counterparty) will broadcast in
118         /// order to close the channel if a channel party goes away. Setting this value too high will
119         /// cause immediate force-closures in order to avoid having an unbroadcastable state.
120         ///
121         /// This feerate represents the fee we pick now, which must be sufficient to enter a block at an
122         /// arbitrary time in the future. Obviously this is not an estimate which is very easy to
123         /// calculate. This can leave channels subject to being unable to close if feerates rise, and in
124         /// general you should prefer anchor channels to ensure you can increase the feerate when the
125         /// transactions need broadcasting.
126         ///
127         /// Do note some fee estimators round up to the next full sat/vbyte (ie 250 sats per kw),
128         /// causing occasional issues with feerate disagreements between an initiator that wants a
129         /// feerate of 1.1 sat/vbyte and a receiver that wants 1.1 rounded up to 2. If your fee
130         /// estimator rounds subtracting 250 to your desired feerate here can help avoid this issue.
131         ///
132         /// [`ChannelConfig::max_dust_htlc_exposure`]: crate::util::config::ChannelConfig::max_dust_htlc_exposure
133         MinAllowedNonAnchorChannelRemoteFee,
134         /// This is the feerate on the transaction which we (or our counterparty) will broadcast in
135         /// order to close the channel if a channel party goes away.
136         ///
137         /// This needs to be sufficient to get into the mempool when the channel needs to
138         /// be force-closed. Setting too low may result in force-closures. Because this is for anchor
139         /// channels, it can be a low value as we can always bump the feerate later.
140         ///
141         /// A good estimate is the expected mempool minimum at the time of force-closure. Obviously this
142         /// is not an estimate which is very easy to calculate because we do not know the future. Using
143         /// a simple long-term fee estimate or tracking of the mempool minimum is a good approach to
144         /// ensure you can always close the channel. A future change to Bitcoin's P2P network
145         /// (package relay) may obviate the need for this entirely.
146         AnchorChannelFee,
147         /// Lightning is built around the ability to broadcast a transaction in the future to close our
148         /// channel and claim all pending funds. In order to do so, non-anchor channels are built with
149         /// transactions which we need to be able to broadcast at some point in the future.
150         ///
151         /// This feerate represents the fee we pick now, which must be sufficient to enter a block at an
152         /// arbitrary time in the future. Obviously this is not an estimate which is very easy to
153         /// calculate, so most lightning nodes use some relatively high-priority feerate using the
154         /// current mempool. This leaves channels subject to being unable to close if feerates rise, and
155         /// in general you should prefer anchor channels to ensure you can increase the feerate when the
156         /// transactions need broadcasting.
157         ///
158         /// Since this should represent the feerate of a channel close that does not need fee
159         /// bumping, this is also used as an upper bound for our attempted feerate when doing cooperative
160         /// closure of any channel.
161         NonAnchorChannelFee,
162         /// When cooperatively closing a channel, this is the minimum feerate we will accept.
163         /// Recommended at least within a day or so worth of blocks.
164         ///
165         /// This will also be used when initiating a cooperative close of a channel. When closing a
166         /// channel you can override this fee by using
167         /// [`ChannelManager::close_channel_with_feerate_and_script`].
168         ///
169         /// [`ChannelManager::close_channel_with_feerate_and_script`]: crate::ln::channelmanager::ChannelManager::close_channel_with_feerate_and_script
170         ChannelCloseMinimum,
171         /// The feerate [`OutputSweeper`] will use on transactions spending
172         /// [`SpendableOutputDescriptor`]s after a channel closure.
173         ///
174         /// Generally spending these outputs is safe as long as they eventually confirm, so a value
175         /// (slightly above) the mempool minimum should suffice. However, as this value will influence
176         /// how long funds will be unavailable after channel closure, [`FeeEstimator`] implementors
177         /// might want to choose a higher feerate to regain control over funds faster.
178         ///
179         /// [`OutputSweeper`]: crate::util::sweep::OutputSweeper
180         /// [`SpendableOutputDescriptor`]: crate::sign::SpendableOutputDescriptor
181         OutputSpendingFee,
182 }
183 use lightning::chain::chaininterface::ConfirmationTarget as ConfirmationTargetImport;
184 pub(crate) type nativeConfirmationTarget = ConfirmationTargetImport;
185
186 impl ConfirmationTarget {
187         #[allow(unused)]
188         pub(crate) fn to_native(&self) -> nativeConfirmationTarget {
189                 match self {
190                         ConfirmationTarget::OnChainSweep => nativeConfirmationTarget::OnChainSweep,
191                         ConfirmationTarget::MinAllowedAnchorChannelRemoteFee => nativeConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
192                         ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => nativeConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
193                         ConfirmationTarget::AnchorChannelFee => nativeConfirmationTarget::AnchorChannelFee,
194                         ConfirmationTarget::NonAnchorChannelFee => nativeConfirmationTarget::NonAnchorChannelFee,
195                         ConfirmationTarget::ChannelCloseMinimum => nativeConfirmationTarget::ChannelCloseMinimum,
196                         ConfirmationTarget::OutputSpendingFee => nativeConfirmationTarget::OutputSpendingFee,
197                 }
198         }
199         #[allow(unused)]
200         pub(crate) fn into_native(self) -> nativeConfirmationTarget {
201                 match self {
202                         ConfirmationTarget::OnChainSweep => nativeConfirmationTarget::OnChainSweep,
203                         ConfirmationTarget::MinAllowedAnchorChannelRemoteFee => nativeConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
204                         ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => nativeConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
205                         ConfirmationTarget::AnchorChannelFee => nativeConfirmationTarget::AnchorChannelFee,
206                         ConfirmationTarget::NonAnchorChannelFee => nativeConfirmationTarget::NonAnchorChannelFee,
207                         ConfirmationTarget::ChannelCloseMinimum => nativeConfirmationTarget::ChannelCloseMinimum,
208                         ConfirmationTarget::OutputSpendingFee => nativeConfirmationTarget::OutputSpendingFee,
209                 }
210         }
211         #[allow(unused)]
212         pub(crate) fn from_native(native: &ConfirmationTargetImport) -> Self {
213                 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeConfirmationTarget) };
214                 match native {
215                         nativeConfirmationTarget::OnChainSweep => ConfirmationTarget::OnChainSweep,
216                         nativeConfirmationTarget::MinAllowedAnchorChannelRemoteFee => ConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
217                         nativeConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
218                         nativeConfirmationTarget::AnchorChannelFee => ConfirmationTarget::AnchorChannelFee,
219                         nativeConfirmationTarget::NonAnchorChannelFee => ConfirmationTarget::NonAnchorChannelFee,
220                         nativeConfirmationTarget::ChannelCloseMinimum => ConfirmationTarget::ChannelCloseMinimum,
221                         nativeConfirmationTarget::OutputSpendingFee => ConfirmationTarget::OutputSpendingFee,
222                 }
223         }
224         #[allow(unused)]
225         pub(crate) fn native_into(native: nativeConfirmationTarget) -> Self {
226                 match native {
227                         nativeConfirmationTarget::OnChainSweep => ConfirmationTarget::OnChainSweep,
228                         nativeConfirmationTarget::MinAllowedAnchorChannelRemoteFee => ConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
229                         nativeConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
230                         nativeConfirmationTarget::AnchorChannelFee => ConfirmationTarget::AnchorChannelFee,
231                         nativeConfirmationTarget::NonAnchorChannelFee => ConfirmationTarget::NonAnchorChannelFee,
232                         nativeConfirmationTarget::ChannelCloseMinimum => ConfirmationTarget::ChannelCloseMinimum,
233                         nativeConfirmationTarget::OutputSpendingFee => ConfirmationTarget::OutputSpendingFee,
234                 }
235         }
236 }
237 /// Creates a copy of the ConfirmationTarget
238 #[no_mangle]
239 pub extern "C" fn ConfirmationTarget_clone(orig: &ConfirmationTarget) -> ConfirmationTarget {
240         orig.clone()
241 }
242 #[allow(unused)]
243 /// Used only if an object of this type is returned as a trait impl by a method
244 pub(crate) extern "C" fn ConfirmationTarget_clone_void(this_ptr: *const c_void) -> *mut c_void {
245         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const ConfirmationTarget)).clone() })) as *mut c_void
246 }
247 #[allow(unused)]
248 /// Used only if an object of this type is returned as a trait impl by a method
249 pub(crate) extern "C" fn ConfirmationTarget_free_void(this_ptr: *mut c_void) {
250         let _ = unsafe { Box::from_raw(this_ptr as *mut ConfirmationTarget) };
251 }
252 #[no_mangle]
253 /// Utility method to constructs a new OnChainSweep-variant ConfirmationTarget
254 pub extern "C" fn ConfirmationTarget_on_chain_sweep() -> ConfirmationTarget {
255         ConfirmationTarget::OnChainSweep}
256 #[no_mangle]
257 /// Utility method to constructs a new MinAllowedAnchorChannelRemoteFee-variant ConfirmationTarget
258 pub extern "C" fn ConfirmationTarget_min_allowed_anchor_channel_remote_fee() -> ConfirmationTarget {
259         ConfirmationTarget::MinAllowedAnchorChannelRemoteFee}
260 #[no_mangle]
261 /// Utility method to constructs a new MinAllowedNonAnchorChannelRemoteFee-variant ConfirmationTarget
262 pub extern "C" fn ConfirmationTarget_min_allowed_non_anchor_channel_remote_fee() -> ConfirmationTarget {
263         ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee}
264 #[no_mangle]
265 /// Utility method to constructs a new AnchorChannelFee-variant ConfirmationTarget
266 pub extern "C" fn ConfirmationTarget_anchor_channel_fee() -> ConfirmationTarget {
267         ConfirmationTarget::AnchorChannelFee}
268 #[no_mangle]
269 /// Utility method to constructs a new NonAnchorChannelFee-variant ConfirmationTarget
270 pub extern "C" fn ConfirmationTarget_non_anchor_channel_fee() -> ConfirmationTarget {
271         ConfirmationTarget::NonAnchorChannelFee}
272 #[no_mangle]
273 /// Utility method to constructs a new ChannelCloseMinimum-variant ConfirmationTarget
274 pub extern "C" fn ConfirmationTarget_channel_close_minimum() -> ConfirmationTarget {
275         ConfirmationTarget::ChannelCloseMinimum}
276 #[no_mangle]
277 /// Utility method to constructs a new OutputSpendingFee-variant ConfirmationTarget
278 pub extern "C" fn ConfirmationTarget_output_spending_fee() -> ConfirmationTarget {
279         ConfirmationTarget::OutputSpendingFee}
280 /// Get a string which allows debug introspection of a ConfirmationTarget object
281 pub extern "C" fn ConfirmationTarget_debug_str_void(o: *const c_void) -> Str {
282         alloc::format!("{:?}", unsafe { o as *const crate::lightning::chain::chaininterface::ConfirmationTarget }).into()}
283 /// Generates a non-cryptographic 64-bit hash of the ConfirmationTarget.
284 #[no_mangle]
285 pub extern "C" fn ConfirmationTarget_hash(o: &ConfirmationTarget) -> u64 {
286         // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
287         #[allow(deprecated)]
288         let mut hasher = core::hash::SipHasher::new();
289         core::hash::Hash::hash(&o.to_native(), &mut hasher);
290         core::hash::Hasher::finish(&hasher)
291 }
292 /// Checks if two ConfirmationTargets contain equal inner contents.
293 /// This ignores pointers and is_owned flags and looks at the values in fields.
294 #[no_mangle]
295 pub extern "C" fn ConfirmationTarget_eq(a: &ConfirmationTarget, b: &ConfirmationTarget) -> bool {
296         if &a.to_native() == &b.to_native() { true } else { false }
297 }
298 /// A trait which should be implemented to provide feerate information on a number of time
299 /// horizons.
300 ///
301 /// If access to a local mempool is not feasible, feerate estimates should be fetched from a set of
302 /// third-parties hosting them. Note that this enables them to affect the propagation of your
303 /// pre-signed transactions at any time and therefore endangers the safety of channels funds. It
304 /// should be considered carefully as a deployment.
305 ///
306 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
307 /// called from inside the library in response to chain events, P2P events, or timer events).
308 ///
309 /// LDK may generate a substantial number of fee-estimation calls in some cases. You should
310 /// pre-calculate and cache the fee estimate results to ensure you don't substantially slow HTLC
311 /// handling.
312 #[repr(C)]
313 pub struct FeeEstimator {
314         /// An opaque pointer which is passed to your function implementations as an argument.
315         /// This has no meaning in the LDK, and can be NULL or any other value.
316         pub this_arg: *mut c_void,
317         /// Gets estimated satoshis of fee required per 1000 Weight-Units.
318         ///
319         /// LDK will wrap this method and ensure that the value returned is no smaller than 253
320         /// (ie 1 satoshi-per-byte rounded up to ensure later round-downs don't put us below 1 satoshi-per-byte).
321         ///
322         /// The following unit conversions can be used to convert to sats/KW:
323         ///  * satoshis-per-byte * 250
324         ///  * satoshis-per-kbyte / 4
325         pub get_est_sat_per_1000_weight: extern "C" fn (this_arg: *const c_void, confirmation_target: crate::lightning::chain::chaininterface::ConfirmationTarget) -> u32,
326         /// Frees any resources associated with this object given its this_arg pointer.
327         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
328         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
329 }
330 unsafe impl Send for FeeEstimator {}
331 unsafe impl Sync for FeeEstimator {}
332 #[allow(unused)]
333 pub(crate) fn FeeEstimator_clone_fields(orig: &FeeEstimator) -> FeeEstimator {
334         FeeEstimator {
335                 this_arg: orig.this_arg,
336                 get_est_sat_per_1000_weight: Clone::clone(&orig.get_est_sat_per_1000_weight),
337                 free: Clone::clone(&orig.free),
338         }
339 }
340
341 use lightning::chain::chaininterface::FeeEstimator as rustFeeEstimator;
342 impl rustFeeEstimator for FeeEstimator {
343         fn get_est_sat_per_1000_weight(&self, mut confirmation_target: lightning::chain::chaininterface::ConfirmationTarget) -> u32 {
344                 let mut ret = (self.get_est_sat_per_1000_weight)(self.this_arg, crate::lightning::chain::chaininterface::ConfirmationTarget::native_into(confirmation_target));
345                 ret
346         }
347 }
348
349 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
350 // directly as a Deref trait in higher-level structs:
351 impl core::ops::Deref for FeeEstimator {
352         type Target = Self;
353         fn deref(&self) -> &Self {
354                 self
355         }
356 }
357 impl core::ops::DerefMut for FeeEstimator {
358         fn deref_mut(&mut self) -> &mut Self {
359                 self
360         }
361 }
362 /// Calls the free function if one is set
363 #[no_mangle]
364 pub extern "C" fn FeeEstimator_free(this_ptr: FeeEstimator) { }
365 impl Drop for FeeEstimator {
366         fn drop(&mut self) {
367                 if let Some(f) = self.free {
368                         f(self.this_arg);
369                 }
370         }
371 }
372 /// Minimum relay fee as required by bitcoin network mempool policy.
373
374 #[no_mangle]
375 pub static MIN_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = lightning::chain::chaininterface::MIN_RELAY_FEE_SAT_PER_1000_WEIGHT;
376 /// Minimum feerate that takes a sane approach to bitcoind weight-to-vbytes rounding.
377 /// See the following Core Lightning commit for an explanation:
378 /// <https://github.com/ElementsProject/lightning/commit/2e687b9b352c9092b5e8bd4a688916ac50b44af0>
379
380 #[no_mangle]
381 pub static FEERATE_FLOOR_SATS_PER_KW: u32 = lightning::chain::chaininterface::FEERATE_FLOOR_SATS_PER_KW;