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