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 //! Traits and utility impls which allow other parts of rust-lightning to interact with the
12 //! Includes traits for monitoring and receiving notifications of new blocks and block
13 //! disconnections, transaction broadcasting, and feerate information requests.
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};
24 /// An interface to send a transaction to the Bitcoin network.
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.
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.
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.
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)>,
48 unsafe impl Send for BroadcasterInterface {}
49 unsafe impl Sync for BroadcasterInterface {}
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),
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())
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 {
71 fn deref(&self) -> &Self {
75 impl core::ops::DerefMut for BroadcasterInterface {
76 fn deref_mut(&mut self) -> &mut Self {
80 /// Calls the free function if one is set
82 pub extern "C" fn BroadcasterInterface_free(this_ptr: BroadcasterInterface) { }
83 impl Drop for BroadcasterInterface {
85 if let Some(f) = self.free {
90 /// An enum that represents the priority at which we want a transaction to confirm used for feerate
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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`].
169 /// [`ChannelManager::close_channel_with_feerate_and_script`]: crate::ln::channelmanager::ChannelManager::close_channel_with_feerate_and_script
172 use lightning::chain::chaininterface::ConfirmationTarget as ConfirmationTargetImport;
173 pub(crate) type nativeConfirmationTarget = ConfirmationTargetImport;
175 impl ConfirmationTarget {
177 pub(crate) fn to_native(&self) -> nativeConfirmationTarget {
179 ConfirmationTarget::OnChainSweep => nativeConfirmationTarget::OnChainSweep,
180 ConfirmationTarget::MinAllowedAnchorChannelRemoteFee => nativeConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
181 ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => nativeConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
182 ConfirmationTarget::AnchorChannelFee => nativeConfirmationTarget::AnchorChannelFee,
183 ConfirmationTarget::NonAnchorChannelFee => nativeConfirmationTarget::NonAnchorChannelFee,
184 ConfirmationTarget::ChannelCloseMinimum => nativeConfirmationTarget::ChannelCloseMinimum,
188 pub(crate) fn into_native(self) -> nativeConfirmationTarget {
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,
199 pub(crate) fn from_native(native: &ConfirmationTargetImport) -> Self {
200 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeConfirmationTarget) };
202 nativeConfirmationTarget::OnChainSweep => ConfirmationTarget::OnChainSweep,
203 nativeConfirmationTarget::MinAllowedAnchorChannelRemoteFee => ConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
204 nativeConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
205 nativeConfirmationTarget::AnchorChannelFee => ConfirmationTarget::AnchorChannelFee,
206 nativeConfirmationTarget::NonAnchorChannelFee => ConfirmationTarget::NonAnchorChannelFee,
207 nativeConfirmationTarget::ChannelCloseMinimum => ConfirmationTarget::ChannelCloseMinimum,
211 pub(crate) fn native_into(native: nativeConfirmationTarget) -> Self {
213 nativeConfirmationTarget::OnChainSweep => ConfirmationTarget::OnChainSweep,
214 nativeConfirmationTarget::MinAllowedAnchorChannelRemoteFee => ConfirmationTarget::MinAllowedAnchorChannelRemoteFee,
215 nativeConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee,
216 nativeConfirmationTarget::AnchorChannelFee => ConfirmationTarget::AnchorChannelFee,
217 nativeConfirmationTarget::NonAnchorChannelFee => ConfirmationTarget::NonAnchorChannelFee,
218 nativeConfirmationTarget::ChannelCloseMinimum => ConfirmationTarget::ChannelCloseMinimum,
222 /// Creates a copy of the ConfirmationTarget
224 pub extern "C" fn ConfirmationTarget_clone(orig: &ConfirmationTarget) -> ConfirmationTarget {
228 /// Used only if an object of this type is returned as a trait impl by a method
229 pub(crate) extern "C" fn ConfirmationTarget_clone_void(this_ptr: *const c_void) -> *mut c_void {
230 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const ConfirmationTarget)).clone() })) as *mut c_void
233 /// Used only if an object of this type is returned as a trait impl by a method
234 pub(crate) extern "C" fn ConfirmationTarget_free_void(this_ptr: *mut c_void) {
235 let _ = unsafe { Box::from_raw(this_ptr as *mut ConfirmationTarget) };
238 /// Utility method to constructs a new OnChainSweep-variant ConfirmationTarget
239 pub extern "C" fn ConfirmationTarget_on_chain_sweep() -> ConfirmationTarget {
240 ConfirmationTarget::OnChainSweep}
242 /// Utility method to constructs a new MinAllowedAnchorChannelRemoteFee-variant ConfirmationTarget
243 pub extern "C" fn ConfirmationTarget_min_allowed_anchor_channel_remote_fee() -> ConfirmationTarget {
244 ConfirmationTarget::MinAllowedAnchorChannelRemoteFee}
246 /// Utility method to constructs a new MinAllowedNonAnchorChannelRemoteFee-variant ConfirmationTarget
247 pub extern "C" fn ConfirmationTarget_min_allowed_non_anchor_channel_remote_fee() -> ConfirmationTarget {
248 ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee}
250 /// Utility method to constructs a new AnchorChannelFee-variant ConfirmationTarget
251 pub extern "C" fn ConfirmationTarget_anchor_channel_fee() -> ConfirmationTarget {
252 ConfirmationTarget::AnchorChannelFee}
254 /// Utility method to constructs a new NonAnchorChannelFee-variant ConfirmationTarget
255 pub extern "C" fn ConfirmationTarget_non_anchor_channel_fee() -> ConfirmationTarget {
256 ConfirmationTarget::NonAnchorChannelFee}
258 /// Utility method to constructs a new ChannelCloseMinimum-variant ConfirmationTarget
259 pub extern "C" fn ConfirmationTarget_channel_close_minimum() -> ConfirmationTarget {
260 ConfirmationTarget::ChannelCloseMinimum}
261 /// Get a string which allows debug introspection of a ConfirmationTarget object
262 pub extern "C" fn ConfirmationTarget_debug_str_void(o: *const c_void) -> Str {
263 alloc::format!("{:?}", unsafe { o as *const crate::lightning::chain::chaininterface::ConfirmationTarget }).into()}
264 /// Generates a non-cryptographic 64-bit hash of the ConfirmationTarget.
266 pub extern "C" fn ConfirmationTarget_hash(o: &ConfirmationTarget) -> u64 {
267 // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
269 let mut hasher = core::hash::SipHasher::new();
270 core::hash::Hash::hash(&o.to_native(), &mut hasher);
271 core::hash::Hasher::finish(&hasher)
273 /// Checks if two ConfirmationTargets contain equal inner contents.
274 /// This ignores pointers and is_owned flags and looks at the values in fields.
276 pub extern "C" fn ConfirmationTarget_eq(a: &ConfirmationTarget, b: &ConfirmationTarget) -> bool {
277 if &a.to_native() == &b.to_native() { true } else { false }
279 /// A trait which should be implemented to provide feerate information on a number of time
282 /// If access to a local mempool is not feasible, feerate estimates should be fetched from a set of
283 /// third-parties hosting them. Note that this enables them to affect the propagation of your
284 /// pre-signed transactions at any time and therefore endangers the safety of channels funds. It
285 /// should be considered carefully as a deployment.
287 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
288 /// called from inside the library in response to chain events, P2P events, or timer events).
290 pub struct FeeEstimator {
291 /// An opaque pointer which is passed to your function implementations as an argument.
292 /// This has no meaning in the LDK, and can be NULL or any other value.
293 pub this_arg: *mut c_void,
294 /// Gets estimated satoshis of fee required per 1000 Weight-Units.
296 /// LDK will wrap this method and ensure that the value returned is no smaller than 253
297 /// (ie 1 satoshi-per-byte rounded up to ensure later round-downs don't put us below 1 satoshi-per-byte).
299 /// The following unit conversions can be used to convert to sats/KW:
300 /// * satoshis-per-byte * 250
301 /// * satoshis-per-kbyte / 4
302 pub get_est_sat_per_1000_weight: extern "C" fn (this_arg: *const c_void, confirmation_target: crate::lightning::chain::chaininterface::ConfirmationTarget) -> u32,
303 /// Frees any resources associated with this object given its this_arg pointer.
304 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
305 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
307 unsafe impl Send for FeeEstimator {}
308 unsafe impl Sync for FeeEstimator {}
310 pub(crate) fn FeeEstimator_clone_fields(orig: &FeeEstimator) -> FeeEstimator {
312 this_arg: orig.this_arg,
313 get_est_sat_per_1000_weight: Clone::clone(&orig.get_est_sat_per_1000_weight),
314 free: Clone::clone(&orig.free),
318 use lightning::chain::chaininterface::FeeEstimator as rustFeeEstimator;
319 impl rustFeeEstimator for FeeEstimator {
320 fn get_est_sat_per_1000_weight(&self, mut confirmation_target: lightning::chain::chaininterface::ConfirmationTarget) -> u32 {
321 let mut ret = (self.get_est_sat_per_1000_weight)(self.this_arg, crate::lightning::chain::chaininterface::ConfirmationTarget::native_into(confirmation_target));
326 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
327 // directly as a Deref trait in higher-level structs:
328 impl core::ops::Deref for FeeEstimator {
330 fn deref(&self) -> &Self {
334 impl core::ops::DerefMut for FeeEstimator {
335 fn deref_mut(&mut self) -> &mut Self {
339 /// Calls the free function if one is set
341 pub extern "C" fn FeeEstimator_free(this_ptr: FeeEstimator) { }
342 impl Drop for FeeEstimator {
344 if let Some(f) = self.free {
349 /// Minimum relay fee as required by bitcoin network mempool policy.
352 pub static MIN_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = lightning::chain::chaininterface::MIN_RELAY_FEE_SAT_PER_1000_WEIGHT;
353 /// Minimum feerate that takes a sane approach to bitcoind weight-to-vbytes rounding.
354 /// See the following Core Lightning commit for an explanation:
355 /// <https://github.com/ElementsProject/lightning/commit/2e687b9b352c9092b5e8bd4a688916ac50b44af0>
358 pub static FEERATE_FLOOR_SATS_PER_KW: u32 = lightning::chain::chaininterface::FEERATE_FLOOR_SATS_PER_KW;