lightning/chain/
chaininterface.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
4// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7// You may not use this file except in accordance with one or both of these
8// licenses.
9
10//! Traits and utility impls which allow other parts of rust-lightning to interact with the
11//! blockchain.
12//!
13//! Includes traits for monitoring and receiving notifications of new blocks and block
14//! disconnections, transaction broadcasting, and feerate information requests.
15
16use core::{cmp, ops::Deref};
17
18use crate::prelude::*;
19
20use bitcoin::transaction::Transaction;
21
22// TODO: Define typed abstraction over feerates to handle their conversions.
23pub(crate) fn compute_feerate_sat_per_1000_weight(fee_sat: u64, weight: u64) -> u32 {
24	(fee_sat * 1000 / weight).try_into().unwrap_or(u32::max_value())
25}
26pub(crate) const fn fee_for_weight(feerate_sat_per_1000_weight: u32, weight: u64) -> u64 {
27	((feerate_sat_per_1000_weight as u64 * weight) + 1000 - 1) / 1000
28}
29
30/// An interface to send a transaction to the Bitcoin network.
31pub trait BroadcasterInterface {
32	/// Sends a list of transactions out to (hopefully) be mined.
33	/// This only needs to handle the actual broadcasting of transactions, LDK will automatically
34	/// rebroadcast transactions that haven't made it into a block.
35	///
36	/// In some cases LDK may attempt to broadcast a transaction which double-spends another
37	/// and this isn't a bug and can be safely ignored.
38	///
39	/// If more than one transaction is given, these transactions MUST be a
40	/// single child and its parents and be broadcast together as a package
41	/// (see the [`submitpackage`](https://bitcoincore.org/en/doc/30.0.0/rpc/rawtransactions/submitpackage)
42	/// Bitcoin Core RPC).
43	///
44	/// Implementations MUST NOT assume any topological order on the transactions.
45	///
46	/// Bitcoin transaction packages are defined in BIP 331 and here:
47	/// <https://github.com/bitcoin/bitcoin/blob/master/doc/policy/packages.md>
48	fn broadcast_transactions(&self, txs: &[&Transaction]);
49}
50
51/// An enum that represents the priority at which we want a transaction to confirm used for feerate
52/// estimation.
53#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
54pub enum ConfirmationTarget {
55	/// The most aggressive feerate estimate which we think is reasonable.
56	///
57	/// This is used to sanity-check our counterparty's feerates and should be as conservative as
58	/// possible to ensure that we don't confuse a peer using a very conservative estimator for one
59	/// trying to burn channel balance to dust. To ensure that this is never lower than an honest
60	/// counterparty's feerate estimate you may wish to use a value which is higher than your
61	/// maximum feerate estimate, for example by adding a constant few-hundred or few-thousand
62	/// sats-per-kW.
63	MaximumFeeEstimate,
64	/// We have some funds available on chain which we need to spend prior to some expiry time at
65	/// which point our counterparty may be able to steal them.
66	///
67	/// Generally we have in the high tens to low hundreds of blocks to get our transaction
68	/// on-chain (it doesn't have to happen in the next few blocks!), but we shouldn't risk too low
69	/// a fee - this should be a relatively high priority feerate.
70	UrgentOnChainSweep,
71	/// This is the lowest feerate we will allow our channel counterparty to have in an anchor
72	/// channel in order to close the channel if a channel party goes away.
73	///
74	/// This needs to be sufficient to get into the mempool when the channel needs to
75	/// be force-closed. Setting too high may result in force-closures if our counterparty attempts
76	/// to use a lower feerate. Because this is for anchor channels, we can always bump the feerate
77	/// later; the feerate here only needs to be sufficient to enter the mempool.
78	///
79	/// A good estimate is the expected mempool minimum at the time of force-closure. Obviously this
80	/// is not an estimate which is very easy to calculate because we do not know the future. Using
81	/// a simple long-term fee estimate or tracking of the mempool minimum is a good approach to
82	/// ensure you can always close the channel. A future change to Bitcoin's P2P network
83	/// (package relay) may obviate the need for this entirely.
84	MinAllowedAnchorChannelRemoteFee,
85	/// The lowest feerate we will allow our channel counterparty to have in a non-anchor channel.
86	///
87	/// This is the feerate on the transaction which we (or our counterparty) will broadcast in
88	/// order to close the channel if a channel party goes away. Setting this value too high will
89	/// cause immediate force-closures in order to avoid having an unbroadcastable state.
90	///
91	/// This feerate represents the fee we pick now, which must be sufficient to enter a block at an
92	/// arbitrary time in the future. Obviously this is not an estimate which is very easy to
93	/// calculate. This can leave channels subject to being unable to close if feerates rise, and in
94	/// general you should prefer anchor channels to ensure you can increase the feerate when the
95	/// transactions need broadcasting.
96	///
97	/// Do note some fee estimators round up to the next full sat/vbyte (ie 250 sats per kw),
98	/// causing occasional issues with feerate disagreements between an initiator that wants a
99	/// feerate of 1.1 sat/vbyte and a receiver that wants 1.1 rounded up to 2. If your fee
100	/// estimator rounds subtracting 250 to your desired feerate here can help avoid this issue.
101	///
102	/// [`ChannelConfig::max_dust_htlc_exposure`]: crate::util::config::ChannelConfig::max_dust_htlc_exposure
103	MinAllowedNonAnchorChannelRemoteFee,
104	/// This is the feerate on the transaction which we (or our counterparty) will broadcast in
105	/// order to close the channel if a channel party goes away.
106	///
107	/// This needs to be sufficient to get into the mempool when the channel needs to
108	/// be force-closed. Setting too low may result in force-closures. Because this is for anchor
109	/// channels, it can be a low value as we can always bump the feerate later.
110	///
111	/// A good estimate is the expected mempool minimum at the time of force-closure. Obviously this
112	/// is not an estimate which is very easy to calculate because we do not know the future. Using
113	/// a simple long-term fee estimate or tracking of the mempool minimum is a good approach to
114	/// ensure you can always close the channel. A future change to Bitcoin's P2P network
115	/// (package relay) may obviate the need for this entirely.
116	AnchorChannelFee,
117	/// Lightning is built around the ability to broadcast a transaction in the future to close our
118	/// channel and claim all pending funds. In order to do so, non-anchor channels are built with
119	/// transactions which we need to be able to broadcast at some point in the future.
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, so most lightning nodes use some relatively high-priority feerate using the
124	/// current mempool. This leaves channels subject to being unable to close if feerates rise, and
125	/// in general you should prefer anchor channels to ensure you can increase the feerate when the
126	/// transactions need broadcasting.
127	///
128	/// Since this should represent the feerate of a channel close that does not need fee
129	/// bumping, this is also used as an upper bound for our attempted feerate when doing cooperative
130	/// closure of any channel.
131	NonAnchorChannelFee,
132	/// When cooperatively closing a channel, this is the minimum feerate we will accept.
133	/// Recommended at least within a day or so worth of blocks.
134	///
135	/// This will also be used when initiating a cooperative close of a channel. When closing a
136	/// channel you can override this fee by using
137	/// [`ChannelManager::close_channel_with_feerate_and_script`].
138	///
139	/// [`ChannelManager::close_channel_with_feerate_and_script`]: crate::ln::channelmanager::ChannelManager::close_channel_with_feerate_and_script
140	ChannelCloseMinimum,
141	/// The feerate used to claim on-chain funds when there is no particular urgency to do so.
142	///
143	/// It is used to get commitment transactions without any HTLCs confirmed in [`ChannelMonitor`]
144	/// and by  [`OutputSweeper`] on transactions spending [`SpendableOutputDescriptor`]s after a
145	/// channel closure.
146	///
147	/// Generally spending these outputs is safe as long as they eventually confirm, so a value
148	/// (slightly above) the mempool minimum should suffice. However, as this value will influence
149	/// how long funds will be unavailable after channel closure, [`FeeEstimator`] implementors
150	/// might want to choose a higher feerate to regain control over funds faster.
151	///
152	/// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
153	/// [`OutputSweeper`]: crate::util::sweep::OutputSweeper
154	/// [`SpendableOutputDescriptor`]: crate::sign::SpendableOutputDescriptor
155	OutputSpendingFee,
156}
157
158/// A trait which should be implemented to provide feerate information on a number of time
159/// horizons.
160///
161/// If access to a local mempool is not feasible, feerate estimates should be fetched from a set of
162/// third-parties hosting them. Note that this enables them to affect the propagation of your
163/// pre-signed transactions at any time and therefore endangers the safety of channels funds. It
164/// should be considered carefully as a deployment.
165///
166/// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
167/// called from inside the library in response to chain events, P2P events, or timer events).
168///
169/// LDK may generate a substantial number of fee-estimation calls in some cases. You should
170/// pre-calculate and cache the fee estimate results to ensure you don't substantially slow HTLC
171/// handling.
172pub trait FeeEstimator {
173	/// Gets estimated satoshis of fee required per 1000 Weight-Units.
174	///
175	/// LDK will wrap this method and ensure that the value returned is no smaller than 253
176	/// (ie 1 satoshi-per-byte rounded up to ensure later round-downs don't put us below 1 satoshi-per-byte).
177	///
178	/// The following unit conversions can be used to convert to sats/KW:
179	///  * satoshis-per-byte * 250
180	///  * satoshis-per-kbyte / 4
181	fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32;
182}
183
184/// Minimum relay fee as required by bitcoin network mempool policy.
185pub const INCREMENTAL_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = 253;
186/// Minimum feerate that takes a sane approach to bitcoind weight-to-vbytes rounding.
187/// See the following Core Lightning commit for an explanation:
188/// <https://github.com/ElementsProject/lightning/commit/2e687b9b352c9092b5e8bd4a688916ac50b44af0>
189pub const FEERATE_FLOOR_SATS_PER_KW: u32 = 253;
190
191/// Wraps a `Deref` to a `FeeEstimator` so that any fee estimations provided by it
192/// are bounded below by `FEERATE_FLOOR_SATS_PER_KW` (253 sats/KW).
193///
194/// Note that this does *not* implement [`FeeEstimator`] to make it harder to accidentally mix the
195/// two.
196pub(crate) struct LowerBoundedFeeEstimator<F: Deref>(pub F)
197where
198	F::Target: FeeEstimator;
199
200impl<F: Deref> LowerBoundedFeeEstimator<F>
201where
202	F::Target: FeeEstimator,
203{
204	/// Creates a new `LowerBoundedFeeEstimator` which wraps the provided fee_estimator
205	pub fn new(fee_estimator: F) -> Self {
206		LowerBoundedFeeEstimator(fee_estimator)
207	}
208
209	pub fn bounded_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
210		cmp::max(self.0.get_est_sat_per_1000_weight(confirmation_target), FEERATE_FLOOR_SATS_PER_KW)
211	}
212}
213
214#[cfg(test)]
215mod tests {
216	use super::{
217		ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator, FEERATE_FLOOR_SATS_PER_KW,
218	};
219
220	struct TestFeeEstimator {
221		sat_per_kw: u32,
222	}
223
224	impl FeeEstimator for TestFeeEstimator {
225		fn get_est_sat_per_1000_weight(&self, _: ConfirmationTarget) -> u32 {
226			self.sat_per_kw
227		}
228	}
229
230	#[test]
231	fn test_fee_estimator_less_than_floor() {
232		let sat_per_kw = FEERATE_FLOOR_SATS_PER_KW - 1;
233		let test_fee_estimator = &TestFeeEstimator { sat_per_kw };
234		let fee_estimator = LowerBoundedFeeEstimator::new(test_fee_estimator);
235
236		assert_eq!(
237			fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee),
238			FEERATE_FLOOR_SATS_PER_KW
239		);
240	}
241
242	#[test]
243	fn test_fee_estimator_greater_than_floor() {
244		let sat_per_kw = FEERATE_FLOOR_SATS_PER_KW + 1;
245		let test_fee_estimator = &TestFeeEstimator { sat_per_kw };
246		let fee_estimator = LowerBoundedFeeEstimator::new(test_fee_estimator);
247
248		assert_eq!(
249			fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee),
250			sat_per_kw
251		);
252	}
253}