dfb90135c88de84b2d9fe962c9e05d354cbab86b
[rust-lightning] / lightning / src / 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
16 use core::{cmp, ops::Deref};
17 use core::convert::TryInto;
18
19 use bitcoin::blockdata::transaction::Transaction;
20
21 // TODO: Define typed abstraction over feerates to handle their conversions.
22 pub(crate) fn compute_feerate_sat_per_1000_weight(fee_sat: u64, weight: u64) -> u32 {
23         (fee_sat * 1000 / weight).try_into().unwrap_or(u32::max_value())
24 }
25 pub(crate) const fn fee_for_weight(feerate_sat_per_1000_weight: u32, weight: u64) -> u64 {
26         ((feerate_sat_per_1000_weight as u64 * weight) + 1000 - 1) / 1000
27 }
28
29 /// An interface to send a transaction to the Bitcoin network.
30 pub trait BroadcasterInterface {
31         /// Sends a list of transactions out to (hopefully) be mined.
32         /// This only needs to handle the actual broadcasting of transactions, LDK will automatically
33         /// rebroadcast transactions that haven't made it into a block.
34         ///
35         /// In some cases LDK may attempt to broadcast a transaction which double-spends another
36         /// and this isn't a bug and can be safely ignored.
37         ///
38         /// If more than one transaction is given, these transactions should be considered to be a
39         /// package and broadcast together. Some of the transactions may or may not depend on each other,
40         /// be sure to manage both cases correctly.
41         ///
42         /// Bitcoin transaction packages are defined in BIP 331 and here:
43         /// https://github.com/bitcoin/bitcoin/blob/master/doc/policy/packages.md
44         fn broadcast_transactions(&self, txs: &[&Transaction]);
45 }
46
47 /// An enum that represents the priority at which we want a transaction to confirm used for feerate
48 /// estimation.
49 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
50 pub enum ConfirmationTarget {
51         /// We have some funds available on chain which we need to spend prior to some expiry time at
52         /// which point our counterparty may be able to steal them. Generally we have in the high tens
53         /// to low hundreds of blocks to get our transaction on-chain, but we shouldn't risk too low a
54         /// fee - this should be a relatively high priority feerate.
55         OnChainSweep,
56         /// The highest feerate we will allow our channel counterparty to have in a non-anchor channel.
57         ///
58         /// This is the feerate on the transaction which we (or our counterparty) will broadcast in
59         /// order to close the channel unilaterally. Because our counterparty must ensure they can
60         /// always broadcast the latest state, this value being too low will cause immediate
61         /// force-closures.
62         ///
63         /// Allowing this value to be too high can allow our counterparty to burn our HTLC outputs to
64         /// dust, which can result in HTLCs failing or force-closures (when the dust HTLCs exceed
65         /// [`ChannelConfig::max_dust_htlc_exposure`]).
66         ///
67         /// Because most nodes use a feerate estimate which is based on a relatively high priority
68         /// transaction entering the current mempool, setting this to a small multiple of your current
69         /// high priority feerate estimate should suffice.
70         ///
71         /// [`ChannelConfig::max_dust_htlc_exposure`]: crate::util::config::ChannelConfig::max_dust_htlc_exposure
72         MaxAllowedNonAnchorChannelRemoteFee,
73         /// This is the lowest feerate we will allow our channel counterparty to have in an anchor
74         /// channel in order to close the channel if a channel party goes away. Because our counterparty
75         /// must ensure they can always broadcast the latest state, this value being too high will cause
76         /// immediate force-closures.
77         ///
78         /// This needs to be sufficient to get into the mempool when the channel needs to
79         /// be force-closed. Setting too low may result in force-closures. Because this is for anchor
80         /// channels, we can always bump the feerate later, the feerate here only needs to suffice to
81         /// enter the mempool.
82         ///
83         /// A good estimate is the expected mempool minimum at the time of force-closure. Obviously this
84         /// is not an estimate which is very easy to calculate because we do not know the future. Using
85         /// a simple long-term fee estimate or tracking of the mempool minimum is a good approach to
86         /// ensure you can always close the channel. A future change to Bitcoin's P2P network
87         /// (package relay) may obviate the need for this entirely.
88         MinAllowedAnchorChannelRemoteFee,
89         /// The lowest feerate we will allow our channel counterparty to have in a non-anchor channel.
90         /// This needs to be sufficient to get confirmed when the channel needs to be force-closed.
91         /// Setting too low may result in force-closures.
92         ///
93         /// This is the feerate on the transaction which we (or our counterparty) will broadcast in
94         /// order to close the channel if a channel party goes away. Because our counterparty must
95         /// ensure they can always broadcast the latest state, this value being too high will cause
96         /// immediate force-closures.
97         ///
98         /// This feerate represents the fee we pick now, which must be sufficient to enter a block at an
99         /// arbitrary time in the future. Obviously this is not an estimate which is very easy to
100         /// calculate. This can leave channels subject to being unable to close if feerates rise, and in
101         /// general you should prefer anchor channels to ensure you can increase the feerate when the
102         /// transactions need broadcasting.
103         ///
104         /// Do note some fee estimators round up to the next full sat/vbyte (ie 250 sats per kw),
105         /// causing occasional issues with feerate disagreements between an initiator that wants a
106         /// feerate of 1.1 sat/vbyte and a receiver that wants 1.1 rounded up to 2. If your fee
107         /// estimator rounds subtracting 250 to your desired feerate here can help avoid this issue.
108         ///
109         /// [`ChannelConfig::max_dust_htlc_exposure`]: crate::util::config::ChannelConfig::max_dust_htlc_exposure
110         MinAllowedNonAnchorChannelRemoteFee,
111         /// This is the feerate on the transaction which we (or our counterparty) will broadcast in
112         /// order to close the channel if a channel party goes away.
113         ///
114         /// This needs to be sufficient to get into the mempool when the channel needs to
115         /// be force-closed. Setting too low may result in force-closures. Because this is for anchor
116         /// channels, it can be a low value as we can always bump the feerate later.
117         ///
118         /// A good estimate is the expected mempool minimum at the time of force-closure. Obviously this
119         /// is not an estimate which is very easy to calculate because we do not know the future. Using
120         /// a simple long-term fee estimate or tracking of the mempool minimum is a good approach to
121         /// ensure you can always close the channel. A future change to Bitcoin's P2P network
122         /// (package relay) may obviate the need for this entirely.
123         AnchorChannelFee,
124         /// Lightning is built around the ability to broadcast a transaction in the future to close our
125         /// channel and claim all pending funds. In order to do so, non-anchor channels are built with
126         /// transactions which we need to be able to broadcast at some point in the future.
127         ///
128         /// This feerate represents the fee we pick now, which must be sufficient to enter a block at an
129         /// arbitrary time in the future. Obviously this is not an estimate which is very easy to
130         /// calculate, so most lightning nodes use some relatively high-priority feerate using the
131         /// current mempool. This leaves channels subject to being unable to close if feerates rise, and
132         /// in general you should prefer anchor channels to ensure you can increase the feerate when the
133         /// transactions need broadcasting.
134         ///
135         /// Since this should represent the feerate of a channel close that does not need fee
136         /// bumping, this is also used as an upper bound for our attempted feerate when doing cooperative
137         /// closure of any channel.
138         NonAnchorChannelFee,
139         /// When cooperatively closing a channel, this is the minimum feerate we will accept.
140         /// Recommended at least within a day or so worth of blocks.
141         ///
142         /// This will also be used when initiating a cooperative close of a channel. When closing a
143         /// channel you can override this fee by using
144         /// [`ChannelManager::close_channel_with_feerate_and_script`].
145         ///
146         /// [`ChannelManager::close_channel_with_feerate_and_script`]: crate::ln::channelmanager::ChannelManager::close_channel_with_feerate_and_script
147         ChannelCloseMinimum,
148 }
149
150 /// A trait which should be implemented to provide feerate information on a number of time
151 /// horizons.
152 ///
153 /// If access to a local mempool is not feasible, feerate estimates should be fetched from a set of
154 /// third-parties hosting them. Note that this enables them to affect the propagation of your
155 /// pre-signed transactions at any time and therefore endangers the safety of channels funds. It
156 /// should be considered carefully as a deployment.
157 ///
158 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
159 /// called from inside the library in response to chain events, P2P events, or timer events).
160 pub trait FeeEstimator {
161         /// Gets estimated satoshis of fee required per 1000 Weight-Units.
162         ///
163         /// LDK will wrap this method and ensure that the value returned is no smaller than 253
164         /// (ie 1 satoshi-per-byte rounded up to ensure later round-downs don't put us below 1 satoshi-per-byte).
165         ///
166         /// The following unit conversions can be used to convert to sats/KW:
167         ///  * satoshis-per-byte * 250
168         ///  * satoshis-per-kbyte / 4
169         fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32;
170 }
171
172 /// Minimum relay fee as required by bitcoin network mempool policy.
173 pub const MIN_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = 4000;
174 /// Minimum feerate that takes a sane approach to bitcoind weight-to-vbytes rounding.
175 /// See the following Core Lightning commit for an explanation:
176 /// <https://github.com/ElementsProject/lightning/commit/2e687b9b352c9092b5e8bd4a688916ac50b44af0>
177 pub const FEERATE_FLOOR_SATS_PER_KW: u32 = 253;
178
179 /// Wraps a `Deref` to a `FeeEstimator` so that any fee estimations provided by it
180 /// are bounded below by `FEERATE_FLOOR_SATS_PER_KW` (253 sats/KW).
181 ///
182 /// Note that this does *not* implement [`FeeEstimator`] to make it harder to accidentally mix the
183 /// two.
184 pub(crate) struct LowerBoundedFeeEstimator<F: Deref>(pub F) where F::Target: FeeEstimator;
185
186 impl<F: Deref> LowerBoundedFeeEstimator<F> where F::Target: FeeEstimator {
187         /// Creates a new `LowerBoundedFeeEstimator` which wraps the provided fee_estimator
188         pub fn new(fee_estimator: F) -> Self {
189                 LowerBoundedFeeEstimator(fee_estimator)
190         }
191
192         pub fn bounded_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
193                 cmp::max(
194                         self.0.get_est_sat_per_1000_weight(confirmation_target),
195                         FEERATE_FLOOR_SATS_PER_KW,
196                 )
197         }
198 }
199
200 #[cfg(test)]
201 mod tests {
202         use super::{FEERATE_FLOOR_SATS_PER_KW, LowerBoundedFeeEstimator, ConfirmationTarget, FeeEstimator};
203
204         struct TestFeeEstimator {
205                 sat_per_kw: u32,
206         }
207
208         impl FeeEstimator for TestFeeEstimator {
209                 fn get_est_sat_per_1000_weight(&self, _: ConfirmationTarget) -> u32 {
210                         self.sat_per_kw
211                 }
212         }
213
214         #[test]
215         fn test_fee_estimator_less_than_floor() {
216                 let sat_per_kw = FEERATE_FLOOR_SATS_PER_KW - 1;
217                 let test_fee_estimator = &TestFeeEstimator { sat_per_kw };
218                 let fee_estimator = LowerBoundedFeeEstimator::new(test_fee_estimator);
219
220                 assert_eq!(fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee), FEERATE_FLOOR_SATS_PER_KW);
221         }
222
223         #[test]
224         fn test_fee_estimator_greater_than_floor() {
225                 let sat_per_kw = FEERATE_FLOOR_SATS_PER_KW + 1;
226                 let test_fee_estimator = &TestFeeEstimator { sat_per_kw };
227                 let fee_estimator = LowerBoundedFeeEstimator::new(test_fee_estimator);
228
229                 assert_eq!(fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee), sat_per_kw);
230         }
231 }