lightning/util/
config.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//! Various user-configurable channel limits and settings which ChannelManager
11//! applies for you.
12
13use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
14use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT};
15
16#[cfg(fuzzing)]
17use crate::util::ser::Readable;
18
19/// Configuration we set when applicable.
20///
21/// `Default::default()` provides sane defaults.
22#[derive(Copy, Clone, Debug)]
23pub struct ChannelHandshakeConfig {
24	/// Confirmations we will wait for before considering the channel locked in.
25	/// Applied only for inbound channels (see [`ChannelHandshakeLimits::max_minimum_depth`] for the
26	/// equivalent limit applied to outbound channels).
27	///
28	/// A lower-bound of `1` is applied, requiring all channels to have a confirmed commitment
29	/// transaction before operation. If you wish to accept channels with zero confirmations, see
30	/// [`UserConfig::manually_accept_inbound_channels`] and
31	/// [`ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`].
32	///
33	/// Default value: `6`
34	///
35	/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
36	/// [`ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf
37	pub minimum_depth: u32,
38	/// Set to the number of blocks we require our counterparty to wait to claim their money (ie
39	/// the number of blocks we have to punish our counterparty if they broadcast a revoked
40	/// transaction).
41	///
42	/// This is one of the main parameters of our security model. We (or one of our watchtowers) MUST
43	/// be online to check for revoked transactions on-chain at least once every our_to_self_delay
44	/// blocks (minus some margin to allow us enough time to broadcast and confirm a transaction,
45	/// possibly with time in between to RBF the spending transaction).
46	///
47	/// Meanwhile, asking for a too high delay, we bother peer to freeze funds for nothing in
48	/// case of an honest unilateral channel close, which implicitly decrease the economic value of
49	/// our channel.
50	///
51	/// Default value: [`BREAKDOWN_TIMEOUT`] (We enforce it as a minimum at channel opening so you
52	/// can tweak config to ask for more security, not less.)
53	pub our_to_self_delay: u16,
54	/// Set to the smallest value HTLC we will accept to process.
55	///
56	/// This value is sent to our counterparty on channel-open and we close the channel any time
57	/// our counterparty misbehaves by sending us an HTLC with a value smaller than this.
58	///
59	/// Default value: `1` (If the value is less than `1`, it is ignored and set to `1`, as is
60	/// required by the protocol.
61	pub our_htlc_minimum_msat: u64,
62	/// Sets the percentage of the channel value we will cap the total value of outstanding inbound
63	/// HTLCs to.
64	///
65	/// This can be set to a value between 1-100, where the value corresponds to the percent of the
66	/// channel value in whole percentages.
67	///
68	/// Note that:
69	/// * If configured to another value than the default value `10`, any new channels created with
70	///   the non default value will cause versions of LDK prior to 0.0.104 to refuse to read the
71	///   `ChannelManager`.
72	///
73	/// * This caps the total value for inbound HTLCs in-flight only, and there's currently
74	///   no way to configure the cap for the total value of outbound HTLCs in-flight.
75	///
76	/// * The requirements for your node being online to ensure the safety of HTLC-encumbered funds
77	///   are different from the non-HTLC-encumbered funds. This makes this an important knob to
78	///   restrict exposure to loss due to being offline for too long.
79	///   See [`ChannelHandshakeConfig::our_to_self_delay`] and [`ChannelConfig::cltv_expiry_delta`]
80	///   for more information.
81	///
82	/// Default value: `10`
83	///
84	/// Minimum value: `1` (Any values less will be treated as `1` instead.)
85	///
86	/// Maximum value: `100` (Any values larger will be treated as `100` instead.)
87	pub max_inbound_htlc_value_in_flight_percent_of_channel: u8,
88	/// If set, we attempt to negotiate the `scid_privacy` (referred to as `scid_alias` in the
89	/// BOLTs) option for outbound private channels. This provides better privacy by not including
90	/// our real on-chain channel UTXO in each invoice and requiring that our counterparty only
91	/// relay HTLCs to us using the channel's SCID alias.
92	///
93	/// If this option is set, channels may be created that will not be readable by LDK versions
94	/// prior to 0.0.106, causing [`ChannelManager`]'s read method to return a
95	/// [`DecodeError::InvalidValue`].
96	///
97	/// Note that setting this to true does *not* prevent us from opening channels with
98	/// counterparties that do not support the `scid_alias` option; we will simply fall back to a
99	/// private channel without that option.
100	///
101	/// Ignored if the channel is negotiated to be announced, see
102	/// [`ChannelHandshakeConfig::announce_for_forwarding`] and
103	/// [`ChannelHandshakeLimits::force_announced_channel_preference`] for more.
104	///
105	/// Default value: `false` (This value is likely to change to `true` in the future.)
106	///
107	/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
108	/// [`DecodeError::InvalidValue`]: crate::ln::msgs::DecodeError::InvalidValue
109	pub negotiate_scid_privacy: bool,
110	/// Set to announce the channel publicly and notify all nodes that they can route via this
111	/// channel.
112	///
113	/// This should only be set to true for nodes which expect to be online reliably.
114	///
115	/// As the node which funds a channel picks this value this will only apply for new outbound
116	/// channels unless [`ChannelHandshakeLimits::force_announced_channel_preference`] is set.
117	///
118	/// Default value: `false`
119	pub announce_for_forwarding: bool,
120	/// When set, we commit to an upfront shutdown_pubkey at channel open. If our counterparty
121	/// supports it, they will then enforce the mutual-close output to us matches what we provided
122	/// at intialization, preventing us from closing to an alternate pubkey.
123	///
124	/// This is set to true by default to provide a slight increase in security, though ultimately
125	/// any attacker who is able to take control of a channel can just as easily send the funds via
126	/// lightning payments, so we never require that our counterparties support this option.
127	///
128	/// The upfront key committed is provided from [`SignerProvider::get_shutdown_scriptpubkey`].
129	///
130	/// Default value: `true`
131	///
132	/// [`SignerProvider::get_shutdown_scriptpubkey`]: crate::sign::SignerProvider::get_shutdown_scriptpubkey
133	pub commit_upfront_shutdown_pubkey: bool,
134	/// The Proportion of the channel value to configure as counterparty's channel reserve,
135	/// i.e., `their_channel_reserve_satoshis` for both outbound and inbound channels.
136	///
137	/// `their_channel_reserve_satoshis` is the minimum balance that the other node has to maintain
138	/// on their side, at all times.
139	/// This ensures that if our counterparty broadcasts a revoked state, we can punish them by
140	/// claiming at least this value on chain.
141	///
142	/// Channel reserve values greater than 30% could be considered highly unreasonable, since that
143	/// amount can never be used for payments.
144	/// Also, if our selected channel reserve for counterparty and counterparty's selected
145	/// channel reserve for us sum up to equal or greater than channel value, channel negotiations
146	/// will fail.
147	///
148	/// Note: Versions of LDK earlier than v0.0.104 will fail to read channels with any channel reserve
149	/// other than the default value.
150	///
151	/// Default value: `10_000` millionths (i.e., 1% of channel value)
152	///
153	/// Minimum value: If the calculated proportional value is less than `1000` sats, it will be
154	///                treated as `1000` sats instead, which is a safe implementation-specific lower
155	///                bound.
156	///
157	/// Maximum value: `1_000_000` (i.e., 100% of channel value. Any values larger than one million
158	///                will be treated as one million instead, although channel negotiations will
159	///                fail in that case.)
160	pub their_channel_reserve_proportional_millionths: u32,
161	/// If set, we attempt to negotiate the `anchors_zero_fee_htlc_tx`option for all future
162	/// channels. This feature requires having a reserve of onchain funds readily available to bump
163	/// transactions in the event of a channel force close to avoid the possibility of losing funds.
164	///
165	/// Note that if you wish accept inbound channels with anchor outputs, you must enable
166	/// [`UserConfig::manually_accept_inbound_channels`] and manually accept them with
167	/// [`ChannelManager::accept_inbound_channel`]. This is done to give you the chance to check
168	/// whether your reserve of onchain funds is enough to cover the fees for all existing and new
169	/// channels featuring anchor outputs in the event of a force close.
170	///
171	/// If this option is set, channels may be created that will not be readable by LDK versions
172	/// prior to 0.0.116, causing [`ChannelManager`]'s read method to return a
173	/// [`DecodeError::InvalidValue`].
174	///
175	/// Note that setting this to true does *not* prevent us from opening channels with
176	/// counterparties that do not support the `anchors_zero_fee_htlc_tx` option; we will simply
177	/// fall back to a `static_remote_key` channel.
178	///
179	/// LDK will not support the legacy `option_anchors` commitment version due to a discovered
180	/// vulnerability after its deployment. For more context, see the [`SIGHASH_SINGLE + update_fee
181	/// Considered Harmful`] mailing list post.
182	///
183	/// Default value: `false` (This value is likely to change to `true` in the future.)
184	///
185	/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
186	/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
187	/// [`DecodeError::InvalidValue`]: crate::ln::msgs::DecodeError::InvalidValue
188	/// [`SIGHASH_SINGLE + update_fee Considered Harmful`]: https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-September/002796.html
189	pub negotiate_anchors_zero_fee_htlc_tx: bool,
190
191	/// The maximum number of HTLCs in-flight from our counterparty towards us at the same time.
192	///
193	/// Increasing the value can help improve liquidity and stability in
194	/// routing at the cost of higher long term disk / DB usage.
195	///
196	/// Note: Versions of LDK earlier than v0.0.115 will fail to read channels with a configuration
197	/// other than the default value.
198	///
199	/// Default value: `50`
200	///
201	/// Maximum value: `483` (Any values larger will be treated as `483`. This is the BOLT #2 spec
202	/// limit on `max_accepted_htlcs`.)
203	pub our_max_accepted_htlcs: u16,
204}
205
206impl Default for ChannelHandshakeConfig {
207	fn default() -> ChannelHandshakeConfig {
208		ChannelHandshakeConfig {
209			minimum_depth: 6,
210			our_to_self_delay: BREAKDOWN_TIMEOUT,
211			our_htlc_minimum_msat: 1,
212			max_inbound_htlc_value_in_flight_percent_of_channel: 10,
213			negotiate_scid_privacy: false,
214			announce_for_forwarding: false,
215			commit_upfront_shutdown_pubkey: true,
216			their_channel_reserve_proportional_millionths: 10_000,
217			negotiate_anchors_zero_fee_htlc_tx: false,
218			our_max_accepted_htlcs: 50,
219		}
220	}
221}
222
223// When fuzzing, we want to allow the fuzzer to pick any configuration parameters. Thus, we
224// implement Readable here in a naive way (which is a bit easier for the fuzzer to handle). We
225// don't really want to ever expose this to users (if we did we'd want to use TLVs).
226#[cfg(fuzzing)]
227impl Readable for ChannelHandshakeConfig {
228	fn read<R: crate::io::Read>(reader: &mut R) -> Result<Self, crate::ln::msgs::DecodeError> {
229		Ok(Self {
230			minimum_depth: Readable::read(reader)?,
231			our_to_self_delay: Readable::read(reader)?,
232			our_htlc_minimum_msat: Readable::read(reader)?,
233			max_inbound_htlc_value_in_flight_percent_of_channel: Readable::read(reader)?,
234			negotiate_scid_privacy: Readable::read(reader)?,
235			announce_for_forwarding: Readable::read(reader)?,
236			commit_upfront_shutdown_pubkey: Readable::read(reader)?,
237			their_channel_reserve_proportional_millionths: Readable::read(reader)?,
238			negotiate_anchors_zero_fee_htlc_tx: Readable::read(reader)?,
239			our_max_accepted_htlcs: Readable::read(reader)?,
240		})
241	}
242}
243
244/// Optional channel limits which are applied during channel creation.
245///
246/// These limits are only applied to our counterparty's limits, not our own.
247///
248/// Use `0` or `<type>::max_value()` as appropriate to skip checking.
249///
250/// Provides sane defaults for most configurations.
251///
252/// Most additional limits are disabled except those with which specify a default in individual
253/// field documentation. Note that this may result in barely-usable channels, but since they
254/// are applied mostly only to incoming channels that's not much of a problem.
255#[derive(Copy, Clone, Debug)]
256pub struct ChannelHandshakeLimits {
257	/// Minimum allowed satoshis when a channel is funded. This is supplied by the sender and so
258	/// only applies to inbound channels.
259	///
260	/// Default value: `1000`
261	/// (Minimum of [`ChannelHandshakeConfig::their_channel_reserve_proportional_millionths`])
262	pub min_funding_satoshis: u64,
263	/// Maximum allowed satoshis when a channel is funded. This is supplied by the sender and so
264	/// only applies to inbound channels.
265	///
266	/// Default value: `2^24 - 1`
267	pub max_funding_satoshis: u64,
268	/// The remote node sets a limit on the minimum size of HTLCs we can send to them. This allows
269	/// you to limit the maximum minimum-size they can require.
270	///
271	/// Default value: `u64::max_value`
272	pub max_htlc_minimum_msat: u64,
273	/// The remote node sets a limit on the maximum value of pending HTLCs to them at any given
274	/// time to limit their funds exposure to HTLCs. This allows you to set a minimum such value.
275	///
276	/// Default value: `0`
277	pub min_max_htlc_value_in_flight_msat: u64,
278	/// The remote node will require we keep a certain amount in direct payment to ourselves at all
279	/// time, ensuring that we are able to be punished if we broadcast an old state. This allows to
280	/// you limit the amount which we will have to keep to ourselves (and cannot use for HTLCs).
281	///
282	/// Default value: `u64::max_value`.
283	pub max_channel_reserve_satoshis: u64,
284	/// The remote node sets a limit on the maximum number of pending HTLCs to them at any given
285	/// time. This allows you to set a minimum such value.
286	///
287	/// Default value: `0`
288	pub min_max_accepted_htlcs: u16,
289	/// Before a channel is usable the funding transaction will need to be confirmed by at least a
290	/// certain number of blocks, specified by the node which is not the funder (as the funder can
291	/// assume they aren't going to double-spend themselves).
292	/// This config allows you to set a limit on the maximum amount of time to wait.
293	///
294	/// Default value: `144`, or roughly one day and only applies to outbound channels
295	pub max_minimum_depth: u32,
296	/// Whether we implicitly trust funding transactions generated by us for our own outbound
297	/// channels to not be double-spent.
298	///
299	/// If this is set, we assume that our own funding transactions are *never* double-spent, and
300	/// thus we can trust them without any confirmations. This is generally a reasonable
301	/// assumption, given we're the only ones who could ever double-spend it (assuming we have sole
302	/// control of the signing keys).
303	///
304	/// You may wish to un-set this if you allow the user to (or do in an automated fashion)
305	/// double-spend the funding transaction to RBF with an alternative channel open.
306	///
307	/// This only applies if our counterparty set their confirmations-required value to `0`, and we
308	/// always trust our own funding transaction at `1` confirmation irrespective of this value.
309	/// Thus, this effectively acts as a `min_minimum_depth`, with the only possible values being
310	/// `true` (`0`) and `false` (`1`).
311	///
312	/// Default value: `true`
313	pub trust_own_funding_0conf: bool,
314	/// Set to force an incoming channel to match our announced channel preference in
315	/// [`ChannelHandshakeConfig::announce_for_forwarding`].
316	///
317	/// For a node which is not online reliably, this should be set to true and
318	/// [`ChannelHandshakeConfig::announce_for_forwarding`] set to false, ensuring that no announced (aka public)
319	/// channels will ever be opened.
320	///
321	/// Default value: `true`
322	pub force_announced_channel_preference: bool,
323	/// Set to the amount of time we're willing to wait to claim money back to us.
324	///
325	/// Not checking this value would be a security issue, as our peer would be able to set it to
326	/// max relative lock-time (a year) and we would "lose" money as it would be locked for a long time.
327	///
328	/// Default value: `2016`, which we also enforce as a maximum value so you can tweak config to
329	/// reduce the loss of having useless locked funds (if your peer accepts)
330	pub their_to_self_delay: u16,
331}
332
333impl Default for ChannelHandshakeLimits {
334	fn default() -> Self {
335		ChannelHandshakeLimits {
336			min_funding_satoshis: 1000,
337			max_funding_satoshis: MAX_FUNDING_SATOSHIS_NO_WUMBO,
338			max_htlc_minimum_msat: u64::MAX,
339			min_max_htlc_value_in_flight_msat: 0,
340			max_channel_reserve_satoshis: u64::MAX,
341			min_max_accepted_htlcs: 0,
342			trust_own_funding_0conf: true,
343			max_minimum_depth: 144,
344			force_announced_channel_preference: true,
345			their_to_self_delay: MAX_LOCAL_BREAKDOWN_TIMEOUT,
346		}
347	}
348}
349
350// When fuzzing, we want to allow the fuzzer to pick any configuration parameters. Thus, we
351// implement Readable here in a naive way (which is a bit easier for the fuzzer to handle). We
352// don't really want to ever expose this to users (if we did we'd want to use TLVs).
353#[cfg(fuzzing)]
354impl Readable for ChannelHandshakeLimits {
355	fn read<R: crate::io::Read>(reader: &mut R) -> Result<Self, crate::ln::msgs::DecodeError> {
356		Ok(Self {
357			min_funding_satoshis: Readable::read(reader)?,
358			max_funding_satoshis: Readable::read(reader)?,
359			max_htlc_minimum_msat: Readable::read(reader)?,
360			min_max_htlc_value_in_flight_msat: Readable::read(reader)?,
361			max_channel_reserve_satoshis: Readable::read(reader)?,
362			min_max_accepted_htlcs: Readable::read(reader)?,
363			trust_own_funding_0conf: Readable::read(reader)?,
364			max_minimum_depth: Readable::read(reader)?,
365			force_announced_channel_preference: Readable::read(reader)?,
366			their_to_self_delay: Readable::read(reader)?,
367		})
368	}
369}
370
371/// Options for how to set the max dust exposure allowed on a channel. See
372/// [`ChannelConfig::max_dust_htlc_exposure`] for details.
373#[derive(Copy, Clone, Debug, PartialEq, Eq)]
374pub enum MaxDustHTLCExposure {
375	/// This sets a fixed limit on the total dust exposure in millisatoshis. Setting this too low
376	/// may prevent the sending or receipt of low-value HTLCs on high-traffic nodes, however this
377	/// limit is very important to prevent stealing of large amounts of dust HTLCs by miners
378	/// through [fee griefing
379	/// attacks](https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-May/002714.html).
380	///
381	/// Note that if the feerate increases significantly, without a manual increase
382	/// to this maximum the channel may be unable to send/receive HTLCs between the maximum dust
383	/// exposure and the new minimum value for HTLCs to be economically viable to claim.
384	FixedLimitMsat(u64),
385	/// This sets a multiplier on the [`ConfirmationTarget::MaximumFeeEstimate`] feerate (in
386	/// sats/KW) to determine the maximum allowed dust exposure. If this variant is used then the
387	/// maximum dust exposure in millisatoshis is calculated as:
388	/// `feerate_per_kw * value`. For example, with our default value
389	/// `FeeRateMultiplier(10_000)`:
390	///
391	/// - For the minimum fee rate of 1 sat/vByte (250 sat/KW, although the minimum
392	///   defaults to 253 sats/KW for rounding, see [`FeeEstimator`]), the max dust exposure would
393	///   be 253 * 10_000 = 2,530,000 msats.
394	/// - For a fee rate of 30 sat/vByte (7500 sat/KW), the max dust exposure would be
395	///   7500 * 50_000 = 75,000,000 msats (0.00075 BTC).
396	///
397	/// Note, if you're using a third-party fee estimator, this may leave you more exposed to a
398	/// fee griefing attack, where your fee estimator may purposely overestimate the fee rate,
399	/// causing you to accept more dust HTLCs than you would otherwise.
400	///
401	/// This variant is primarily meant to serve pre-anchor channels, as HTLC fees being included
402	/// on HTLC outputs means your channel may be subject to more dust exposure in the event of
403	/// increases in fee rate.
404	///
405	/// # Backwards Compatibility
406	/// This variant only became available in LDK 0.0.116, so if you downgrade to a prior version
407	/// by default this will be set to a [`Self::FixedLimitMsat`] of 5,000,000 msat.
408	///
409	/// [`FeeEstimator`]: crate::chain::chaininterface::FeeEstimator
410	/// [`ConfirmationTarget::MaximumFeeEstimate`]: crate::chain::chaininterface::ConfirmationTarget::MaximumFeeEstimate
411	FeeRateMultiplier(u64),
412}
413
414impl_writeable_tlv_based_enum_legacy!(MaxDustHTLCExposure, ;
415	(1, FixedLimitMsat),
416	(3, FeeRateMultiplier),
417);
418
419/// Options which apply on a per-channel basis and may change at runtime or based on negotiation
420/// with our counterparty.
421#[derive(Copy, Clone, Debug, PartialEq, Eq)]
422pub struct ChannelConfig {
423	/// Amount (in millionths of a satoshi) charged per satoshi for payments forwarded outbound
424	/// over the channel.
425	/// This may be allowed to change at runtime in a later update, however doing so must result in
426	/// update messages sent to notify all nodes of our updated relay fee.
427	///
428	/// Default value: `0`
429	pub forwarding_fee_proportional_millionths: u32,
430	/// Amount (in milli-satoshi) charged for payments forwarded outbound over the channel, in
431	/// excess of [`forwarding_fee_proportional_millionths`].
432	/// This may be allowed to change at runtime in a later update, however doing so must result in
433	/// update messages sent to notify all nodes of our updated relay fee.
434	///
435	/// The default value of a single satoshi roughly matches the market rate on many routing nodes
436	/// as of July 2021. Adjusting it upwards or downwards may change whether nodes route through
437	/// this node.
438	///
439	/// Default value: `1000`
440	///
441	/// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
442	pub forwarding_fee_base_msat: u32,
443	/// The difference in the CLTV value between incoming HTLCs and an outbound HTLC forwarded over
444	/// the channel this config applies to.
445	///
446	/// This is analogous to [`ChannelHandshakeConfig::our_to_self_delay`] but applies to in-flight
447	/// HTLC balance when a channel appears on-chain whereas
448	/// [`ChannelHandshakeConfig::our_to_self_delay`] applies to the remaining
449	/// (non-HTLC-encumbered) balance.
450	///
451	/// Thus, for HTLC-encumbered balances to be enforced on-chain when a channel is force-closed,
452	/// we (or one of our watchtowers) MUST be online to check for broadcast of the current
453	/// commitment transaction at least once per this many blocks (minus some margin to allow us
454	/// enough time to broadcast and confirm a transaction, possibly with time in between to RBF
455	/// the spending transaction).
456	///
457	/// Default value: `72` (12 hours at an average of 6 blocks/hour)
458	///
459	/// Minimum value: [`MIN_CLTV_EXPIRY_DELTA`] (Any values less than this will be treated as
460	///                [`MIN_CLTV_EXPIRY_DELTA`] instead.)
461	///
462	/// [`MIN_CLTV_EXPIRY_DELTA`]: crate::ln::channelmanager::MIN_CLTV_EXPIRY_DELTA
463	pub cltv_expiry_delta: u16,
464	/// Limit our total exposure to potential loss to on-chain fees on close, including in-flight
465	/// HTLCs which are burned to fees as they are too small to claim on-chain and fees on
466	/// commitment transaction(s) broadcasted by our counterparty in excess of our own fee estimate.
467	///
468	/// # HTLC-based Dust Exposure
469	///
470	/// When an HTLC present in one of our channels is below a "dust" threshold, the HTLC will
471	/// not be claimable on-chain, instead being turned into additional miner fees if either
472	/// party force-closes the channel. Because the threshold is per-HTLC, our total exposure
473	/// to such payments may be substantial if there are many dust HTLCs present when the
474	/// channel is force-closed.
475	///
476	/// The dust threshold for each HTLC is based on the `dust_limit_satoshis` for each party in a
477	/// channel negotiated throughout the channel open process, along with the fees required to have
478	/// a broadcastable HTLC spending transaction. When a channel supports anchor outputs
479	/// (specifically the zero fee HTLC transaction variant), this threshold no longer takes into
480	/// account the HTLC transaction fee as it is zero. Because of this, you may want to set this
481	/// value to a fixed limit for channels using anchor outputs, while the fee rate multiplier
482	/// variant is primarily intended for use with pre-anchor channels.
483	///
484	/// The selected limit is applied for sent, forwarded, and received HTLCs and limits the total
485	/// exposure across all three types per-channel.
486	///
487	/// # Transaction Fee Dust Exposure
488	///
489	/// Further, counterparties broadcasting a commitment transaction in a force-close may result
490	/// in other balance being burned to fees, and thus all fees on commitment and HTLC
491	/// transactions in excess of our local fee estimates are included in the dust calculation.
492	///
493	/// Because of this, another way to look at this limit is to divide it by 43,000 (or 218,750
494	/// for non-anchor channels) and see it as the maximum feerate disagreement (in sats/vB) per
495	/// non-dust HTLC we're allowed to have with our peers before risking a force-closure for
496	/// inbound channels.
497	// This works because, for anchor channels the on-chain cost is 172 weight (172+703 for
498	// non-anchors with an HTLC-Success transaction), i.e.
499	// dust_exposure_limit_msat / 1000 = 172 * feerate_in_sat_per_vb / 4 * HTLC count
500	// dust_exposure_limit_msat = 43,000 * feerate_in_sat_per_vb * HTLC count
501	// dust_exposure_limit_msat / HTLC count / 43,000 = feerate_in_sat_per_vb
502	///
503	/// Thus, for the default value of 10_000 * a current feerate estimate of 10 sat/vB (or 2,500
504	/// sat/KW), we risk force-closure if we disagree with our peer by:
505	/// * `10_000 * 2_500 / 43_000 / (483*2)` = 0.6 sat/vB for anchor channels with 483 HTLCs in
506	///   both directions (the maximum),
507	/// * `10_000 * 2_500 / 43_000 / (50*2)` = 5.8 sat/vB for anchor channels with 50 HTLCs in both
508	///   directions (the LDK default max from [`ChannelHandshakeConfig::our_max_accepted_htlcs`])
509	/// * `10_000 * 2_500 / 218_750 / (483*2)` = 0.1 sat/vB for non-anchor channels with 483 HTLCs
510	///   in both directions (the maximum),
511	/// * `10_000 * 2_500 / 218_750 / (50*2)` = 1.1 sat/vB for non-anchor channels with 50 HTLCs
512	///   in both (the LDK default maximum from [`ChannelHandshakeConfig::our_max_accepted_htlcs`])
513	///
514	/// Note that when using [`MaxDustHTLCExposure::FeeRateMultiplier`] this maximum disagreement
515	/// will scale linearly with increases (or decreases) in the our feerate estimates. Further,
516	/// for anchor channels we expect our counterparty to use a relatively low feerate estimate
517	/// while we use [`ConfirmationTarget::MaximumFeeEstimate`] (which should be relatively high)
518	/// and feerate disagreement force-closures should only occur when theirs is higher than ours.
519	///
520	/// Default value: [`MaxDustHTLCExposure::FeeRateMultiplier`] with a multiplier of `10_000`
521	///
522	/// [`ConfirmationTarget::MaximumFeeEstimate`]: crate::chain::chaininterface::ConfirmationTarget::MaximumFeeEstimate
523	pub max_dust_htlc_exposure: MaxDustHTLCExposure,
524	/// The additional fee we're willing to pay to avoid waiting for the counterparty's
525	/// `to_self_delay` to reclaim funds.
526	///
527	/// When we close a channel cooperatively with our counterparty, we negotiate a fee for the
528	/// closing transaction which both sides find acceptable, ultimately paid by the channel
529	/// funder/initiator.
530	///
531	/// When we are the funder, because we have to pay the channel closing fee, we bound the
532	/// acceptable fee by our [`ChannelCloseMinimum`] and [`NonAnchorChannelFee`] fees, with the upper bound increased by
533	/// this value. Because the on-chain fee we'd pay to force-close the channel is kept near our
534	/// [`NonAnchorChannelFee`] feerate during normal operation, this value represents the additional fee we're
535	/// willing to pay in order to avoid waiting for our counterparty's to_self_delay to reclaim our
536	/// funds.
537	///
538	/// When we are not the funder, we require the closing transaction fee pay at least our
539	/// [`ChannelCloseMinimum`] fee estimate, but allow our counterparty to pay as much fee as they like.
540	/// Thus, this value is ignored when we are not the funder.
541	///
542	/// Default value: `1000`
543	///
544	/// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
545	/// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum
546	pub force_close_avoidance_max_fee_satoshis: u64,
547	/// If set, allows this channel's counterparty to skim an additional fee off this node's inbound
548	/// HTLCs. Useful for liquidity providers to offload on-chain channel costs to end users.
549	///
550	/// Usage:
551	/// - The payee will set this option and set its invoice route hints to use [intercept scids]
552	///   generated by this channel's counterparty.
553	/// - The counterparty will get an [`HTLCIntercepted`] event upon payment forward, and call
554	///   [`forward_intercepted_htlc`] with less than the amount provided in
555	///   [`HTLCIntercepted::expected_outbound_amount_msat`]. The difference between the expected and
556	///   actual forward amounts is their fee. See
557	///   <https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS2#flow-lsp-trusts-client-model>
558	///   for how this feature may be used in the LSP use case.
559	///
560	/// # Note
561	/// It's important for payee wallet software to verify that [`PaymentClaimable::amount_msat`] is
562	/// as-expected if this feature is activated, otherwise they may lose money!
563	/// [`PaymentClaimable::counterparty_skimmed_fee_msat`] provides the fee taken by the
564	/// counterparty.
565	///
566	/// # Note
567	/// Switching this config flag on may break compatibility with versions of LDK prior to 0.0.116.
568	/// Unsetting this flag between restarts may lead to payment receive failures.
569	///
570	/// Default value: `false`
571	///
572	/// [intercept scids]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
573	/// [`forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
574	/// [`HTLCIntercepted`]: crate::events::Event::HTLCIntercepted
575	/// [`HTLCIntercepted::expected_outbound_amount_msat`]: crate::events::Event::HTLCIntercepted::expected_outbound_amount_msat
576	/// [`PaymentClaimable::amount_msat`]: crate::events::Event::PaymentClaimable::amount_msat
577	/// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: crate::events::Event::PaymentClaimable::counterparty_skimmed_fee_msat
578	//  TODO: link to bLIP when it's merged
579	pub accept_underpaying_htlcs: bool,
580}
581
582impl ChannelConfig {
583	/// Applies the given [`ChannelConfigUpdate`] as a partial update to the [`ChannelConfig`].
584	pub fn apply(&mut self, update: &ChannelConfigUpdate) {
585		if let Some(forwarding_fee_proportional_millionths) =
586			update.forwarding_fee_proportional_millionths
587		{
588			self.forwarding_fee_proportional_millionths = forwarding_fee_proportional_millionths;
589		}
590		if let Some(forwarding_fee_base_msat) = update.forwarding_fee_base_msat {
591			self.forwarding_fee_base_msat = forwarding_fee_base_msat;
592		}
593		if let Some(cltv_expiry_delta) = update.cltv_expiry_delta {
594			self.cltv_expiry_delta = cltv_expiry_delta;
595		}
596		if let Some(max_dust_htlc_exposure_msat) = update.max_dust_htlc_exposure_msat {
597			self.max_dust_htlc_exposure = max_dust_htlc_exposure_msat;
598		}
599		if let Some(force_close_avoidance_max_fee_satoshis) =
600			update.force_close_avoidance_max_fee_satoshis
601		{
602			self.force_close_avoidance_max_fee_satoshis = force_close_avoidance_max_fee_satoshis;
603		}
604	}
605}
606
607impl Default for ChannelConfig {
608	/// Provides sane defaults for most configurations (but with zero relay fees!).
609	fn default() -> Self {
610		ChannelConfig {
611			forwarding_fee_proportional_millionths: 0,
612			forwarding_fee_base_msat: 1000,
613			cltv_expiry_delta: 6 * 12, // 6 blocks/hour * 12 hours
614			max_dust_htlc_exposure: MaxDustHTLCExposure::FeeRateMultiplier(10000),
615			force_close_avoidance_max_fee_satoshis: 1000,
616			accept_underpaying_htlcs: false,
617		}
618	}
619}
620
621impl crate::util::ser::Writeable for ChannelConfig {
622	fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
623		let max_dust_htlc_exposure_msat_fixed_limit = match self.max_dust_htlc_exposure {
624			MaxDustHTLCExposure::FixedLimitMsat(limit) => limit,
625			MaxDustHTLCExposure::FeeRateMultiplier(_) => 5_000_000,
626		};
627		write_tlv_fields!(writer, {
628			(0, self.forwarding_fee_proportional_millionths, required),
629			(1, self.accept_underpaying_htlcs, (default_value, false)),
630			(2, self.forwarding_fee_base_msat, required),
631			(3, self.max_dust_htlc_exposure, required),
632			(4, self.cltv_expiry_delta, required),
633			(6, max_dust_htlc_exposure_msat_fixed_limit, required),
634			// ChannelConfig serialized this field with a required type of 8 prior to the introduction of
635			// LegacyChannelConfig. To make sure that serialization is not compatible with this one, we use
636			// the next required type of 10, which if seen by the old serialization will always fail.
637			(10, self.force_close_avoidance_max_fee_satoshis, required),
638		});
639		Ok(())
640	}
641}
642
643impl crate::util::ser::Readable for ChannelConfig {
644	fn read<R: crate::io::Read>(reader: &mut R) -> Result<Self, crate::ln::msgs::DecodeError> {
645		let mut forwarding_fee_proportional_millionths = 0;
646		let mut accept_underpaying_htlcs = false;
647		let mut forwarding_fee_base_msat = 1000;
648		let mut cltv_expiry_delta = 6 * 12;
649		let mut max_dust_htlc_exposure_msat = None;
650		let mut max_dust_htlc_exposure_enum = None;
651		let mut force_close_avoidance_max_fee_satoshis = 1000;
652		read_tlv_fields!(reader, {
653			(0, forwarding_fee_proportional_millionths, required),
654			(1, accept_underpaying_htlcs, (default_value, false)),
655			(2, forwarding_fee_base_msat, required),
656			(3, max_dust_htlc_exposure_enum, option),
657			(4, cltv_expiry_delta, required),
658			// Has always been written, but became optionally read in 0.0.116
659			(6, max_dust_htlc_exposure_msat, option),
660			(10, force_close_avoidance_max_fee_satoshis, required),
661		});
662		let max_dust_htlc_fixed_limit = max_dust_htlc_exposure_msat.unwrap_or(5_000_000);
663		let max_dust_htlc_exposure_msat = max_dust_htlc_exposure_enum
664			.unwrap_or(MaxDustHTLCExposure::FixedLimitMsat(max_dust_htlc_fixed_limit));
665		Ok(Self {
666			forwarding_fee_proportional_millionths,
667			accept_underpaying_htlcs,
668			forwarding_fee_base_msat,
669			cltv_expiry_delta,
670			max_dust_htlc_exposure: max_dust_htlc_exposure_msat,
671			force_close_avoidance_max_fee_satoshis,
672		})
673	}
674}
675
676/// A parallel struct to [`ChannelConfig`] to define partial updates.
677#[allow(missing_docs)]
678#[derive(Default)]
679pub struct ChannelConfigUpdate {
680	pub forwarding_fee_proportional_millionths: Option<u32>,
681	pub forwarding_fee_base_msat: Option<u32>,
682	pub cltv_expiry_delta: Option<u16>,
683	pub max_dust_htlc_exposure_msat: Option<MaxDustHTLCExposure>,
684	pub force_close_avoidance_max_fee_satoshis: Option<u64>,
685}
686
687impl From<ChannelConfig> for ChannelConfigUpdate {
688	fn from(config: ChannelConfig) -> ChannelConfigUpdate {
689		ChannelConfigUpdate {
690			forwarding_fee_proportional_millionths: Some(
691				config.forwarding_fee_proportional_millionths,
692			),
693			forwarding_fee_base_msat: Some(config.forwarding_fee_base_msat),
694			cltv_expiry_delta: Some(config.cltv_expiry_delta),
695			max_dust_htlc_exposure_msat: Some(config.max_dust_htlc_exposure),
696			force_close_avoidance_max_fee_satoshis: Some(
697				config.force_close_avoidance_max_fee_satoshis,
698			),
699		}
700	}
701}
702
703/// Legacy version of [`ChannelConfig`] that stored the static
704/// [`ChannelHandshakeConfig::announce_for_forwarding`] and
705/// [`ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`] fields.
706#[derive(Copy, Clone, Debug)]
707pub(crate) struct LegacyChannelConfig {
708	pub(crate) options: ChannelConfig,
709	/// Deprecated but may still be read from. See [`ChannelHandshakeConfig::announce_for_forwarding`] to
710	/// set this when opening/accepting a channel.
711	pub(crate) announce_for_forwarding: bool,
712	/// Deprecated but may still be read from. See
713	/// [`ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`] to set this when
714	/// opening/accepting a channel.
715	pub(crate) commit_upfront_shutdown_pubkey: bool,
716}
717
718impl Default for LegacyChannelConfig {
719	fn default() -> Self {
720		Self {
721			options: ChannelConfig::default(),
722			announce_for_forwarding: false,
723			commit_upfront_shutdown_pubkey: true,
724		}
725	}
726}
727
728impl crate::util::ser::Writeable for LegacyChannelConfig {
729	fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
730		let max_dust_htlc_exposure_msat_fixed_limit = match self.options.max_dust_htlc_exposure {
731			MaxDustHTLCExposure::FixedLimitMsat(limit) => limit,
732			MaxDustHTLCExposure::FeeRateMultiplier(_) => 5_000_000,
733		};
734		write_tlv_fields!(writer, {
735			(0, self.options.forwarding_fee_proportional_millionths, required),
736			(1, max_dust_htlc_exposure_msat_fixed_limit, required),
737			(2, self.options.cltv_expiry_delta, required),
738			(3, self.options.force_close_avoidance_max_fee_satoshis, (default_value, 1000)),
739			(4, self.announce_for_forwarding, required),
740			(5, self.options.max_dust_htlc_exposure, required),
741			(6, self.commit_upfront_shutdown_pubkey, required),
742			(8, self.options.forwarding_fee_base_msat, required),
743		});
744		Ok(())
745	}
746}
747
748impl crate::util::ser::Readable for LegacyChannelConfig {
749	fn read<R: crate::io::Read>(reader: &mut R) -> Result<Self, crate::ln::msgs::DecodeError> {
750		let mut forwarding_fee_proportional_millionths = 0;
751		let mut max_dust_htlc_exposure_msat_fixed_limit = None;
752		let mut cltv_expiry_delta = 0;
753		let mut force_close_avoidance_max_fee_satoshis = 1000;
754		let mut announce_for_forwarding = false;
755		let mut commit_upfront_shutdown_pubkey = false;
756		let mut forwarding_fee_base_msat = 0;
757		let mut max_dust_htlc_exposure_enum = None;
758		read_tlv_fields!(reader, {
759			(0, forwarding_fee_proportional_millionths, required),
760			// Has always been written, but became optionally read in 0.0.116
761			(1, max_dust_htlc_exposure_msat_fixed_limit, option),
762			(2, cltv_expiry_delta, required),
763			(3, force_close_avoidance_max_fee_satoshis, (default_value, 1000u64)),
764			(4, announce_for_forwarding, required),
765			(5, max_dust_htlc_exposure_enum, option),
766			(6, commit_upfront_shutdown_pubkey, required),
767			(8, forwarding_fee_base_msat, required),
768		});
769		let max_dust_htlc_exposure_msat_fixed_limit =
770			max_dust_htlc_exposure_msat_fixed_limit.unwrap_or(5_000_000);
771		let max_dust_htlc_exposure_msat = max_dust_htlc_exposure_enum.unwrap_or(
772			MaxDustHTLCExposure::FixedLimitMsat(max_dust_htlc_exposure_msat_fixed_limit),
773		);
774		Ok(Self {
775			options: ChannelConfig {
776				forwarding_fee_proportional_millionths,
777				max_dust_htlc_exposure: max_dust_htlc_exposure_msat,
778				cltv_expiry_delta,
779				force_close_avoidance_max_fee_satoshis,
780				forwarding_fee_base_msat,
781				accept_underpaying_htlcs: false,
782			},
783			announce_for_forwarding,
784			commit_upfront_shutdown_pubkey,
785		})
786	}
787}
788
789/// Top-level config which holds ChannelHandshakeLimits and ChannelConfig.
790///
791/// `Default::default()` provides sane defaults for most configurations
792/// (but currently with zero relay fees!)
793#[derive(Copy, Clone, Debug)]
794pub struct UserConfig {
795	/// Channel handshake config that we propose to our counterparty.
796	pub channel_handshake_config: ChannelHandshakeConfig,
797	/// Limits applied to our counterparty's proposed channel handshake config settings.
798	pub channel_handshake_limits: ChannelHandshakeLimits,
799	/// Channel config which affects behavior during channel lifetime.
800	pub channel_config: ChannelConfig,
801	/// If this is set to `false`, we will reject any HTLCs which were to be forwarded over private
802	/// channels. This prevents us from taking on HTLC-forwarding risk when we intend to run as a
803	/// node which is not online reliably.
804	///
805	/// For nodes which are not online reliably, you should set all channels to *not* be announced
806	/// (using [`ChannelHandshakeConfig::announce_for_forwarding`] and
807	/// [`ChannelHandshakeLimits::force_announced_channel_preference`]) and set this to `false` to
808	/// ensure you are not exposed to any forwarding risk.
809	///
810	/// Note that because you cannot change a channel's announced state after creation, there is no
811	/// way to disable forwarding on public channels retroactively. Thus, in order to change a node
812	/// from a publicly-announced forwarding node to a private non-forwarding node you must close
813	/// all your channels and open new ones. For privacy, you should also change your node_id
814	/// (swapping all private and public key material for new ones) at that time.
815	///
816	/// Default value: `false`
817	pub accept_forwards_to_priv_channels: bool,
818	/// If this is set to `false`, we do not accept inbound requests to open a new channel.
819	///
820	/// Default value: `true`
821	pub accept_inbound_channels: bool,
822	/// If this is set to `true`, the user needs to manually accept inbound requests to open a new
823	/// channel.
824	///
825	/// When set to `true`, [`Event::OpenChannelRequest`] will be triggered once a request to open a
826	/// new inbound channel is received through a [`msgs::OpenChannel`] message. In that case, a
827	/// [`msgs::AcceptChannel`] message will not be sent back to the counterparty node unless the
828	/// user explicitly chooses to accept the request.
829	///
830	/// Default value: `false`
831	///
832	/// [`Event::OpenChannelRequest`]: crate::events::Event::OpenChannelRequest
833	/// [`msgs::OpenChannel`]: crate::ln::msgs::OpenChannel
834	/// [`msgs::AcceptChannel`]: crate::ln::msgs::AcceptChannel
835	pub manually_accept_inbound_channels: bool,
836	///  If this is set to `true`, LDK will intercept HTLCs that are attempting to be forwarded over
837	///  fake short channel ids generated via [`ChannelManager::get_intercept_scid`]. Upon HTLC
838	///  intercept, LDK will generate an [`Event::HTLCIntercepted`] which MUST be handled by the user.
839	///
840	///  Setting this to `true` may break backwards compatibility with LDK versions < 0.0.113.
841	///
842	///  Default value: `false`
843	///
844	/// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
845	/// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted
846	pub accept_intercept_htlcs: bool,
847	/// If this is set to `true`, the user needs to manually pay [`Bolt12Invoice`]s when received.
848	///
849	/// When set to `true`, [`Event::InvoiceReceived`] will be generated for each received
850	/// [`Bolt12Invoice`] instead of being automatically paid after verification. Use
851	/// [`ChannelManager::send_payment_for_bolt12_invoice`] to pay the invoice or
852	/// [`ChannelManager::abandon_payment`] to abandon the associated payment.
853	///
854	/// Default value: `false`
855	///
856	/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
857	/// [`Event::InvoiceReceived`]: crate::events::Event::InvoiceReceived
858	/// [`ChannelManager::send_payment_for_bolt12_invoice`]: crate::ln::channelmanager::ChannelManager::send_payment_for_bolt12_invoice
859	/// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
860	pub manually_handle_bolt12_invoices: bool,
861}
862
863impl Default for UserConfig {
864	fn default() -> Self {
865		UserConfig {
866			channel_handshake_config: ChannelHandshakeConfig::default(),
867			channel_handshake_limits: ChannelHandshakeLimits::default(),
868			channel_config: ChannelConfig::default(),
869			accept_forwards_to_priv_channels: false,
870			accept_inbound_channels: true,
871			manually_accept_inbound_channels: false,
872			accept_intercept_htlcs: false,
873			manually_handle_bolt12_invoices: false,
874		}
875	}
876}
877
878// When fuzzing, we want to allow the fuzzer to pick any configuration parameters. Thus, we
879// implement Readable here in a naive way (which is a bit easier for the fuzzer to handle). We
880// don't really want to ever expose this to users (if we did we'd want to use TLVs).
881#[cfg(fuzzing)]
882impl Readable for UserConfig {
883	fn read<R: crate::io::Read>(reader: &mut R) -> Result<Self, crate::ln::msgs::DecodeError> {
884		Ok(Self {
885			channel_handshake_config: Readable::read(reader)?,
886			channel_handshake_limits: Readable::read(reader)?,
887			channel_config: Readable::read(reader)?,
888			accept_forwards_to_priv_channels: Readable::read(reader)?,
889			accept_inbound_channels: Readable::read(reader)?,
890			manually_accept_inbound_channels: Readable::read(reader)?,
891			accept_intercept_htlcs: Readable::read(reader)?,
892			manually_handle_bolt12_invoices: Readable::read(reader)?,
893		})
894	}
895}