47caccbf61a4a301b74ee68185eb36e472caacb8
[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         /// The highest feerate we will allow our channel counterparty to have in a non-anchor channel.
102         ///
103         /// This is the feerate on the transaction which we (or our counterparty) will broadcast in
104         /// order to close the channel unilaterally. Because our counterparty must ensure they can
105         /// always broadcast the latest state, this value being too low will cause immediate
106         /// force-closures.
107         ///
108         /// Allowing this value to be too high can allow our counterparty to burn our HTLC outputs to
109         /// dust, which can result in HTLCs failing or force-closures (when the dust HTLCs exceed
110         /// [`ChannelConfig::max_dust_htlc_exposure`]).
111         ///
112         /// Because most nodes use a feerate estimate which is based on a relatively high priority
113         /// transaction entering the current mempool, setting this to a small multiple of your current
114         /// high priority feerate estimate should suffice.
115         ///
116         /// [`ChannelConfig::max_dust_htlc_exposure`]: crate::util::config::ChannelConfig::max_dust_htlc_exposure
117         MaxAllowedNonAnchorChannelRemoteFee,
118         /// This is the lowest feerate we will allow our channel counterparty to have in an anchor
119         /// channel in order to close the channel if a channel party goes away.
120         ///
121         /// This needs to be sufficient to get into the mempool when the channel needs to
122         /// be force-closed. Setting too high may result in force-closures if our counterparty attempts
123         /// to use a lower feerate. Because this is for anchor channels, we can always bump the feerate
124         /// later; the feerate here only needs to be sufficient to enter the mempool.
125         ///
126         /// A good estimate is the expected mempool minimum at the time of force-closure. Obviously this
127         /// is not an estimate which is very easy to calculate because we do not know the future. Using
128         /// a simple long-term fee estimate or tracking of the mempool minimum is a good approach to
129         /// ensure you can always close the channel. A future change to Bitcoin's P2P network
130         /// (package relay) may obviate the need for this entirely.
131         MinAllowedAnchorChannelRemoteFee,
132         /// The lowest feerate we will allow our channel counterparty to have in a non-anchor channel.
133         ///
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. Setting this value too high will
136         /// cause immediate force-closures in order to avoid having an unbroadcastable state.
137         ///
138         /// This feerate represents the fee we pick now, which must be sufficient to enter a block at an
139         /// arbitrary time in the future. Obviously this is not an estimate which is very easy to
140         /// calculate. This can leave channels subject to being unable to close if feerates rise, and in
141         /// general you should prefer anchor channels to ensure you can increase the feerate when the
142         /// transactions need broadcasting.
143         ///
144         /// Do note some fee estimators round up to the next full sat/vbyte (ie 250 sats per kw),
145         /// causing occasional issues with feerate disagreements between an initiator that wants a
146         /// feerate of 1.1 sat/vbyte and a receiver that wants 1.1 rounded up to 2. If your fee
147         /// estimator rounds subtracting 250 to your desired feerate here can help avoid this issue.
148         ///
149         /// [`ChannelConfig::max_dust_htlc_exposure`]: crate::util::config::ChannelConfig::max_dust_htlc_exposure
150         MinAllowedNonAnchorChannelRemoteFee,
151         /// This is the feerate on the transaction which we (or our counterparty) will broadcast in
152         /// order to close the channel if a channel party goes away.
153         ///
154         /// This needs to be sufficient to get into the mempool when the channel needs to
155         /// be force-closed. Setting too low may result in force-closures. Because this is for anchor
156         /// channels, it can be a low value as we can always bump the feerate later.
157         ///
158         /// A good estimate is the expected mempool minimum at the time of force-closure. Obviously this
159         /// is not an estimate which is very easy to calculate because we do not know the future. Using
160         /// a simple long-term fee estimate or tracking of the mempool minimum is a good approach to
161         /// ensure you can always close the channel. A future change to Bitcoin's P2P network
162         /// (package relay) may obviate the need for this entirely.
163         AnchorChannelFee,
164         /// Lightning is built around the ability to broadcast a transaction in the future to close our
165         /// channel and claim all pending funds. In order to do so, non-anchor channels are built with
166         /// transactions which we need to be able to broadcast at some point in the future.
167         ///
168         /// This feerate represents the fee we pick now, which must be sufficient to enter a block at an
169         /// arbitrary time in the future. Obviously this is not an estimate which is very easy to
170         /// calculate, so most lightning nodes use some relatively high-priority feerate using the
171         /// current mempool. This leaves channels subject to being unable to close if feerates rise, and
172         /// in general you should prefer anchor channels to ensure you can increase the feerate when the
173         /// transactions need broadcasting.
174         ///
175         /// Since this should represent the feerate of a channel close that does not need fee
176         /// bumping, this is also used as an upper bound for our attempted feerate when doing cooperative
177         /// closure of any channel.
178         NonAnchorChannelFee,
179         /// When cooperatively closing a channel, this is the minimum feerate we will accept.
180         /// Recommended at least within a day or so worth of blocks.
181         ///
182         /// This will also be used when initiating a cooperative close of a channel. When closing a
183         /// channel you can override this fee by using
184         /// [`ChannelManager::close_channel_with_feerate_and_script`].
185         ///
186         /// [`ChannelManager::close_channel_with_feerate_and_script`]: crate::ln::channelmanager::ChannelManager::close_channel_with_feerate_and_script
187         ChannelCloseMinimum,
188 }
189 use lightning::chain::chaininterface::ConfirmationTarget as ConfirmationTargetImport;
190 pub(crate) type nativeConfirmationTarget = ConfirmationTargetImport;
191
192 impl ConfirmationTarget {
193         #[allow(unused)]
194         pub(crate) fn to_native(&self) -> nativeConfirmationTarget {
195                 match self {
196                         ConfirmationTarget::OnChainSweep => nativeConfirmationTarget::OnChainSweep,
197                         ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee => nativeConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee,
198                         ConfirmationTarget::MinAllowedAnchorChannelRemoteFee => nativeConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
199                         ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => nativeConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
200                         ConfirmationTarget::AnchorChannelFee => nativeConfirmationTarget::AnchorChannelFee,
201                         ConfirmationTarget::NonAnchorChannelFee => nativeConfirmationTarget::NonAnchorChannelFee,
202                         ConfirmationTarget::ChannelCloseMinimum => nativeConfirmationTarget::ChannelCloseMinimum,
203                 }
204         }
205         #[allow(unused)]
206         pub(crate) fn into_native(self) -> nativeConfirmationTarget {
207                 match self {
208                         ConfirmationTarget::OnChainSweep => nativeConfirmationTarget::OnChainSweep,
209                         ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee => nativeConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee,
210                         ConfirmationTarget::MinAllowedAnchorChannelRemoteFee => nativeConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
211                         ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => nativeConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
212                         ConfirmationTarget::AnchorChannelFee => nativeConfirmationTarget::AnchorChannelFee,
213                         ConfirmationTarget::NonAnchorChannelFee => nativeConfirmationTarget::NonAnchorChannelFee,
214                         ConfirmationTarget::ChannelCloseMinimum => nativeConfirmationTarget::ChannelCloseMinimum,
215                 }
216         }
217         #[allow(unused)]
218         pub(crate) fn from_native(native: &nativeConfirmationTarget) -> Self {
219                 match native {
220                         nativeConfirmationTarget::OnChainSweep => ConfirmationTarget::OnChainSweep,
221                         nativeConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee => ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee,
222                         nativeConfirmationTarget::MinAllowedAnchorChannelRemoteFee => ConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
223                         nativeConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
224                         nativeConfirmationTarget::AnchorChannelFee => ConfirmationTarget::AnchorChannelFee,
225                         nativeConfirmationTarget::NonAnchorChannelFee => ConfirmationTarget::NonAnchorChannelFee,
226                         nativeConfirmationTarget::ChannelCloseMinimum => ConfirmationTarget::ChannelCloseMinimum,
227                 }
228         }
229         #[allow(unused)]
230         pub(crate) fn native_into(native: nativeConfirmationTarget) -> Self {
231                 match native {
232                         nativeConfirmationTarget::OnChainSweep => ConfirmationTarget::OnChainSweep,
233                         nativeConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee => ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee,
234                         nativeConfirmationTarget::MinAllowedAnchorChannelRemoteFee => ConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
235                         nativeConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
236                         nativeConfirmationTarget::AnchorChannelFee => ConfirmationTarget::AnchorChannelFee,
237                         nativeConfirmationTarget::NonAnchorChannelFee => ConfirmationTarget::NonAnchorChannelFee,
238                         nativeConfirmationTarget::ChannelCloseMinimum => ConfirmationTarget::ChannelCloseMinimum,
239                 }
240         }
241 }
242 /// Creates a copy of the ConfirmationTarget
243 #[no_mangle]
244 pub extern "C" fn ConfirmationTarget_clone(orig: &ConfirmationTarget) -> ConfirmationTarget {
245         orig.clone()
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_clone_void(this_ptr: *const c_void) -> *mut c_void {
250         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const ConfirmationTarget)).clone() })) as *mut c_void
251 }
252 #[allow(unused)]
253 /// Used only if an object of this type is returned as a trait impl by a method
254 pub(crate) extern "C" fn ConfirmationTarget_free_void(this_ptr: *mut c_void) {
255         let _ = unsafe { Box::from_raw(this_ptr as *mut ConfirmationTarget) };
256 }
257 #[no_mangle]
258 /// Utility method to constructs a new OnChainSweep-variant ConfirmationTarget
259 pub extern "C" fn ConfirmationTarget_on_chain_sweep() -> ConfirmationTarget {
260         ConfirmationTarget::OnChainSweep}
261 #[no_mangle]
262 /// Utility method to constructs a new MaxAllowedNonAnchorChannelRemoteFee-variant ConfirmationTarget
263 pub extern "C" fn ConfirmationTarget_max_allowed_non_anchor_channel_remote_fee() -> ConfirmationTarget {
264         ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee}
265 #[no_mangle]
266 /// Utility method to constructs a new MinAllowedAnchorChannelRemoteFee-variant ConfirmationTarget
267 pub extern "C" fn ConfirmationTarget_min_allowed_anchor_channel_remote_fee() -> ConfirmationTarget {
268         ConfirmationTarget::MinAllowedAnchorChannelRemoteFee}
269 #[no_mangle]
270 /// Utility method to constructs a new MinAllowedNonAnchorChannelRemoteFee-variant ConfirmationTarget
271 pub extern "C" fn ConfirmationTarget_min_allowed_non_anchor_channel_remote_fee() -> ConfirmationTarget {
272         ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee}
273 #[no_mangle]
274 /// Utility method to constructs a new AnchorChannelFee-variant ConfirmationTarget
275 pub extern "C" fn ConfirmationTarget_anchor_channel_fee() -> ConfirmationTarget {
276         ConfirmationTarget::AnchorChannelFee}
277 #[no_mangle]
278 /// Utility method to constructs a new NonAnchorChannelFee-variant ConfirmationTarget
279 pub extern "C" fn ConfirmationTarget_non_anchor_channel_fee() -> ConfirmationTarget {
280         ConfirmationTarget::NonAnchorChannelFee}
281 #[no_mangle]
282 /// Utility method to constructs a new ChannelCloseMinimum-variant ConfirmationTarget
283 pub extern "C" fn ConfirmationTarget_channel_close_minimum() -> ConfirmationTarget {
284         ConfirmationTarget::ChannelCloseMinimum}
285 /// Generates a non-cryptographic 64-bit hash of the ConfirmationTarget.
286 #[no_mangle]
287 pub extern "C" fn ConfirmationTarget_hash(o: &ConfirmationTarget) -> u64 {
288         // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
289         #[allow(deprecated)]
290         let mut hasher = core::hash::SipHasher::new();
291         core::hash::Hash::hash(&o.to_native(), &mut hasher);
292         core::hash::Hasher::finish(&hasher)
293 }
294 /// Checks if two ConfirmationTargets contain equal inner contents.
295 /// This ignores pointers and is_owned flags and looks at the values in fields.
296 #[no_mangle]
297 pub extern "C" fn ConfirmationTarget_eq(a: &ConfirmationTarget, b: &ConfirmationTarget) -> bool {
298         if &a.to_native() == &b.to_native() { true } else { false }
299 }
300 /// A trait which should be implemented to provide feerate information on a number of time
301 /// horizons.
302 ///
303 /// If access to a local mempool is not feasible, feerate estimates should be fetched from a set of
304 /// third-parties hosting them. Note that this enables them to affect the propagation of your
305 /// pre-signed transactions at any time and therefore endangers the safety of channels funds. It
306 /// should be considered carefully as a deployment.
307 ///
308 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
309 /// called from inside the library in response to chain events, P2P events, or timer events).
310 #[repr(C)]
311 pub struct FeeEstimator {
312         /// An opaque pointer which is passed to your function implementations as an argument.
313         /// This has no meaning in the LDK, and can be NULL or any other value.
314         pub this_arg: *mut c_void,
315         /// Gets estimated satoshis of fee required per 1000 Weight-Units.
316         ///
317         /// LDK will wrap this method and ensure that the value returned is no smaller than 253
318         /// (ie 1 satoshi-per-byte rounded up to ensure later round-downs don't put us below 1 satoshi-per-byte).
319         ///
320         /// The following unit conversions can be used to convert to sats/KW:
321         ///  * satoshis-per-byte * 250
322         ///  * satoshis-per-kbyte / 4
323         pub get_est_sat_per_1000_weight: extern "C" fn (this_arg: *const c_void, confirmation_target: crate::lightning::chain::chaininterface::ConfirmationTarget) -> u32,
324         /// Frees any resources associated with this object given its this_arg pointer.
325         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
326         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
327 }
328 unsafe impl Send for FeeEstimator {}
329 unsafe impl Sync for FeeEstimator {}
330 #[allow(unused)]
331 pub(crate) fn FeeEstimator_clone_fields(orig: &FeeEstimator) -> FeeEstimator {
332         FeeEstimator {
333                 this_arg: orig.this_arg,
334                 get_est_sat_per_1000_weight: Clone::clone(&orig.get_est_sat_per_1000_weight),
335                 free: Clone::clone(&orig.free),
336         }
337 }
338
339 use lightning::chain::chaininterface::FeeEstimator as rustFeeEstimator;
340 impl rustFeeEstimator for FeeEstimator {
341         fn get_est_sat_per_1000_weight(&self, mut confirmation_target: lightning::chain::chaininterface::ConfirmationTarget) -> u32 {
342                 let mut ret = (self.get_est_sat_per_1000_weight)(self.this_arg, crate::lightning::chain::chaininterface::ConfirmationTarget::native_into(confirmation_target));
343                 ret
344         }
345 }
346
347 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
348 // directly as a Deref trait in higher-level structs:
349 impl core::ops::Deref for FeeEstimator {
350         type Target = Self;
351         fn deref(&self) -> &Self {
352                 self
353         }
354 }
355 impl core::ops::DerefMut for FeeEstimator {
356         fn deref_mut(&mut self) -> &mut Self {
357                 self
358         }
359 }
360 /// Calls the free function if one is set
361 #[no_mangle]
362 pub extern "C" fn FeeEstimator_free(this_ptr: FeeEstimator) { }
363 impl Drop for FeeEstimator {
364         fn drop(&mut self) {
365                 if let Some(f) = self.free {
366                         f(self.this_arg);
367                 }
368         }
369 }
370 /// Minimum relay fee as required by bitcoin network mempool policy.
371
372 #[no_mangle]
373 pub static MIN_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = lightning::chain::chaininterface::MIN_RELAY_FEE_SAT_PER_1000_WEIGHT;
374 /// Minimum feerate that takes a sane approach to bitcoind weight-to-vbytes rounding.
375 /// See the following Core Lightning commit for an explanation:
376 /// <https://github.com/ElementsProject/lightning/commit/2e687b9b352c9092b5e8bd4a688916ac50b44af0>
377
378 #[no_mangle]
379 pub static FEERATE_FLOOR_SATS_PER_KW: u32 = lightning::chain::chaininterface::FEERATE_FLOOR_SATS_PER_KW;